为什么输出结果老是带@,而且WHILE不在BEGIN-END循环体中,导致输出结果无法在Pg中运行
```python
import re
import os
def convert_sql_server_to_postgresql(sql):
# 替换 SQL Server 的自增语法
sql = re.sub(r'IDENTITY\(\d+,\s*\d+\)', 'SERIAL', sql)
# 替换 PRINT 为 RAISE NOTICE
sql = re.sub(r'PRINT\s+', 'RAISE NOTICE ', sql)
# 替换变量声明
sql = re.sub(r'DECLARE\s+@(\w+)\s+([A-Z]+)', r'DECLARE \1 \2', sql)
# 替换 SET 语句
sql = re.sub(r'SET\s+@(\w+)\s*=\s*(.+);', r'\1 := \2;', sql)
# 替换 WHILE 循环结构
sql = re.sub(r'WHILE\s+(.+?)\s+BEGIN', r'WHILE \1 LOOP', sql)
sql = re.sub(r'END', 'END LOOP;', sql)
# 处理 SELECT TOP N(这里需要更复杂的处理)
sql = re.sub(r'SELECT TOP (\d+)', r'SELECT', sql)
# 先不直接替换 LIMIT,因为需要处理具体的 SELECT 语句内容
# 其他转换可以继续添加...
# 修改 DECLARE 和其他语法
postgresql_code = sql.replace(';', '')
# 添加 DO 块和结束语句
if "BEGIN" in postgresql_code:
postgresql_code = "DO $$\nDECLARE\n" + postgresql_code.split("BEGIN")[0].strip() + ";\nBEGIN\n" + postgresql_code.split("BEGIN")[1] + "\nEND $$;"
else:
postgresql_code = "DO $$\nBEGIN\n" + postgresql_code + "\nEND $$;"
return postgresql_code
def main():
print("请输入 SQL Server 的 WHILE 循环 SQL 语句(以 `QUIT` 结束):")
sql_server_code = ""
while True:
line = input()
if line.strip().upper() == "QUIT":
break
sql_server_code += line + "\n"
# 转换 SQL 语句
converted_code = convert_sql_server_to_postgresql(sql_server_code)
# 保存转换后的 SQL 语句到输出文件
output_file_path = os.path.join(os.path.expanduser('~'), 'while_loop.sql')
try:
with open(output_file_path, 'w') as file:
file.write(converted_code)
print("转换完成,结果已保存至:", output_file_path)
except Exception as e:
print("保存文件时出错:", e)
if __name__ == "__main__":
main()
输入:
DECLARE @counter INT
SET @counter = 0
WHILE @counter < 10
BEGIN
PRINT @counter
SET @counter = @counter + 1
END
预期输出(pgSQL语句):
DO $$
DECLARE
counter INT;
BEGIN
counter := 0;
WHILE counter < 10 LOOP
RAISE NOTICE 'Counter: %', counter;
counter := counter + 1;
END LOOP;
END $$;
实际输出(pgSQL语句)
DO $$
DECLARE
DECLARE counter INT = 0
WHILE @counter < 5;
BEGIN
RAISE NOTICE @counter
:= @counter = @counter + 1
END
END $$;