使用Vscode外掛SQLTools自動格式化SQL語句

banq發表於2022-03-01

使用 SQL Tools 自動格式化 SQL,
SQLTools 提供的一些功能:
  • 美化器/格式化器
  • 查詢執行器、歷史記錄和書籤
  • 連線瀏覽器
  • 查詢生成器(僅限 INSERT)

首先點選標題下載此SQL 工具。
如果安裝了 DB 驅動程式,則可以將 SQL 檔案直接連線到 DB 並執行。SQLTools 支援的驅動程式
設定 SQL 工具:

SQLTools --設定屬性

編輯.vscode/setting.json:
{
  
    "sqltools.connections": [
    {
        "name": "MySQL",
        "server": "localhost",
        "driver": "MySQL",
        "port": 3306,
        "database": "test_db",
        "username": "root",
        "askForPassword": false,
        "password": "root",
        "connectionTimeout": 15
    }
    ],
   
    "sqltools.format": {
        "language": "sql",
        "indentSize": 2,
        "reservedWordCase": "lower",
        "linesBetweenQueries": 1
    },
   
    "[sql]": {
        "editor.defaultFormatter": "mtxr.sqltools"
    },
    
    "editor.formatOnSave": true
}

在vscode儲存SQL檔案,原來:

SELECT a, b FROM t CROSS JOIN t2 on t.id = t2.id_t;

SELECT DISTINCT name, ROUND(age/7) field1, 18 + 20 AS field2, 'some string' FROM foo;

-- here is a comment
# another comment

UPDATE "log" SET "time" = '2020-02-01 09:00:00' WHERE "id" = 1 RETURNING "time";

CREATE TABLE foo (id INTEGER PRIMARY KEY,name VARCHAR(200) NOT NULL);

ALTER TABLE supplier MODIFY supplier_name char(100) NOT NULL;

select t.column1 Кириллица_cyrilic_alias
  , t.column2 Latin_alias
from db_table t
where a >= some_date1  -- from
and a <  some_date2  -- to
and b >= some_date3  -- and
and b <  some_date4  -- where, select etc.
and 1 = 1;


自動格式化以後:

select a,
    b
from t
    cross join t2 on t.id = t2.id_t;
select distinct name,
    ROUND(age / 7) field1,
    18 + 20 as field2,
    'some string'
from foo;
-- here is a comment
# another comment
update "log"
set "time" = '2020-02-01 09:00:00'
where "id" = 1
returning "time";
create table foo (
    id INTEGER primary key,
    name VARCHAR(200) not null
);
alter table supplier
modify supplier_name char(100) not null;
select t.column1 Кириллица_cyrilic_alias,
    t.column2 Latin_alias
from db_table t
where a >= some_date1 -- from
    and a < some_date2 -- to
    and b >= some_date3 -- and
    and b < some_date4 -- where, select etc.
    and 1 = 1;



 

相關文章