sql文件上的正则表达式

时间:2015-04-26 18:13:41

标签: regex notepad++ sql-scripts

我需要对数百个SQL脚本文件执行搜索和替换操作。我们的想法是改变这个:

CREATE PROCEDURE [dbo].[proc_whatever]
    (
      @id INT,
      @parameter VARCHAR(1)
    )
AS 
    BEGIN
        ...
    END

进入这个:

IF OBJECT_ID('[dbo].[proc_whatever]') IS NULL
      EXEC('CREATE PROCEDURE [dbo].[proc_whatever] AS SET NOCOUNT ON;')
GO

ALTER PROCEDURE [dbo].[proc_whatever]
    (
      @id INT,
      @parameter VARCHAR(1)
    )
AS 
    BEGIN
        ...
    END

为此,我将使用 Notepad ++

任何提示或想法?

2 个答案:

答案 0 :(得分:1)

搜索:

CREATE PROCEDURE ([\[\]a-zA-Z_.]+)\s*\(

替换为:

IF OBJECT_ID \('$1'\) IS NULL \n EXEC \('CREATE PROCEDURE $1  AS SET NOCOUNT ON;'\) \n GO \n ALTER PROCEDURE $1 \(

答案 1 :(得分:1)

您可以使用此正则表达式替换:

Find What:     CREATE\s+PROCEDURE\s+(\[.*?\]\.\[.*?\])\s+\(\s+(@id INT,\s+@parameter VARCHAR\(\d+\)\s+)\s+\)
Replace With:  IF OBJECT_ID\('$1'\) IS NULL\r\n    EXEC\('CREATE PROCEDURE $1 AS SET NOCOUNT ON;'\)\r\nGO\r\n\r\nALTER PROCEDURE $1\r\n    \(\r\n      $2\)

测试:

enter image description here