简体   繁体   中英

Regex - Order Multiline SQL String

Given a string eg:

CREATE TABLE [dbo].[Table1] (
    [Id] [int] NOT NULL,
    [Title] [nvarchar](255) NULL
)

ALTER TABLE [dbo].[Table1] ADD
    CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED ([Id])

INSERT INTO [dbo].[Table1] ([Id], [Title]) VALUES ('Home', NULL)

CREATE TABLE [dbo].[Table2] (
    [Id] [int] NOT NULL,
    [Title] [nvarchar](255) NULL
)

...

How would i go about ordering the statement so that the CREATE TABLE bits are at the top. I'm guessing i would have to use regular expressions but i'm not sure where i go from there.

I'd appreciate the help. Thanks

Create a StringBuilder

Using REGEX

  • Extract TABLE queries and append to StringBuilder
  • Extract INSERT queries and append to StringBuilder
  • Extract ALTER queries and append to StringBuilder

For example you can extract the Create queries using this regular expression:

Regex r = new Regex(@"CREATE .*?(?=(ALTER|INSERT|\z))", RegexOptions.Singleline|RegexOptions.IgnoreCase);
r.Match("CREATE TABLE [dbo]............");

Similarly you can extract ALTER , INSERT queries by merely replacing the ALTER , INSERT , CREATE words in the above regex.

Having fun with LINQ.

var sql = @"CREATE TABLE [dbo].[Table1] (
            [Id] [int] NOT NULL,
            [Title] [nvarchar](255) NULL
        )

        ALTER TABLE [dbo].[Table1] ADD
            CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED ([Id])

        INSERT INTO [dbo].[Table1] ([Id], [Title]) VALUES ('Home', NULL)

        CREATE TABLE [dbo].[Table2] (
            [Id] [int] NOT NULL,
            [Title] [nvarchar](255) NULL
        )
        ";
var statementOrder = new[] { "CREATE", "ALTER", "INSERT" };
var statements = from statement in Regex.Split(sql, "\n\r")
              let trimStatement = statement.Trim()
              let statementType = trimStatement.Substring(0, trimStatement.IndexOf(' '))
              orderby Array.IndexOf(statementOrder, statementType)
              select trimStatement;
var newSql = String.Join("\n\r", statements.ToArray());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM