Remove comments in T-SQL

CSharp · Console

/Program.cs

using System;
					
public class Program
{
	public static void Main()
	{
		//String txtdata = System.IO.File.ReadAllText(@"D:\Temp\test.sql");
		string txtdata = @"
-- 連接 TestDB 資料庫
USE TestDB;
GO
/*
多行註解-1
多行註解-2
多行註解-3
多行註解-4
*/
-- Drop Table
IF ( EXISTS ( SELECT    *
              FROM      INFORMATION_SCHEMA.TABLES
              WHERE     TABLE_NAME = 'Test' ) )
    BEGIN
        TRUNCATE TABLE Test;
        DROP TABLE Test;
    END;
GO
-- Create Table
CREATE TABLE Test
    (
      Id INT PRIMARY KEY
             IDENTITY(1, 1)
             NOT NULL ,
      [Name] NVARCHAR(100) NULL
    );
GO
		";
		Console.WriteLine("原始資料");
		Console.WriteLine("==============================");
		Console.WriteLine(txtdata);
		Console.WriteLine("==============================");

		string pattern = @"(--.*)|(((/\*)+?[\w\W]+?(\*/)+))";
		string result = System.Text.RegularExpressions.Regex.Replace(txtdata, pattern, "");
		Console.WriteLine("處理結果");
		Console.WriteLine("==============================");
		Console.WriteLine(result);
		Console.WriteLine("==============================");
	}
}

/*
參考資料
https://stackoverflow.com/questions/7690380/regular-expression-to-match-all-comments-in-a-t-sql-script

清除後的註解會殘留空白行 (可另外再寫 Regular Expressions 清除一次)
若 SQL Query 內含 -- 字串,則 -- 及其後字串也會被清除,如下
    SELECT * FROM foo WHERE a = 'This has -- dashes'

問題出處 https://www.ptt.cc/bbs/C_Sharp/M.1576937832.A.87D.html
*/
;