【问题标题】:Parse SQL Insert statement and get all string values between N'VALUE'解析 SQL 插入语句并获取 N'VALUE' 之间的所有字符串值
【发布时间】:2020-04-20 03:27:51
【问题描述】:

我有一个大型 SQL Server 插入脚本

INSERT [dbo].[Table] ([Key], [Name], [Value], [Module]) 
VALUES (1, N'Product', N'Value 1', N'Value 2')

现在我需要逐行解析这个大文件,对于每个 NVARCHAR N'VALUEHERE' 值,我想用从数据库中获取的一些自定义信息替换它。

如果这是我的脚本:

INSERT [dbo].[Table] ([Key], [Name], [Value], [Module]) 
VALUES (1, N'Product', N'Value 1', N'Value 2')

解析后我想将其更新为:

INSERT [dbo].[Table] ([Key], [Name], [Value], [Module]) 
VALUES (1, N'Product Changed', N'Value 1 with some custom info', N'Value 2 with different info')

当然,实际情况有点不同。

总的来说,我想获取所有 nvarchar 值,并为每个以 N' 开头的值从单引号中获取该值,对其进行一些操作并使用新值更新它,然后转到下一个 N'等等。

我的问题:

如何获取引号N'VALUE' 之间的每个值更改该值并替换为新值N'CHANGED'

string line = null;


StreamReader file = new System.IO.StreamReader(@"c:\script.sql");  
while((line = file.ReadLine()) != null)  
{  
       // work with `line` here to get each value 
}  

还有一个问题,如果是这样的值,我该如何获取:

 `N'Jimm''s device is broken'`

【问题讨论】:

  • 之后更新数据库即可。
  • 正如我提到的场景有点不同,信息来自休息 api,因此我需要用 C# 来做。当然这会很棒,但我无法直接访问 db,我将从那里获取信息
  • 问题只是如何更新文本文件并替换值,还是涉及将数据取回数据库?
  • @Noel 我现在需要更新 SQL 脚本
  • 我删除了 sql 标签,因为这与 SQL 无关。它是关于转换一个文本文件。

标签: c# regex str-replace regexp-replace


【解决方案1】:

我假设你想对单引号之间的值做一些逻辑。如果你只是想要一个简单的字符串替换,那么正则表达式替换会更好。

您可以使用正则表达式匹配及其捕获组来选择正则表达式匹配的一部分。然后您可以使用捕获组字符串索引值来操作您的原始字符串。

string input = @"INSERT [dbo].[Table] ([Key], [Name], [Value], [Module]) VALUES (1, N'Product', N'Value 1', N'Value 2')";

Regex regex = new Regex("N'([^']+)'");
MatchCollection matches = regex.Matches(input);

//Loop though matches backwards so the index values don't get misaligned
for (int i = matches.Count - 1; i >= 0; i--)
{
    //Get the capture group info for the content between the single quotes
    Group captureGroup = matches[i].Groups[1];

    //Replace the contents of the input string with some updated value
    input = input.Substring(0, captureGroup.Index) + SomeStringMethod(captureGroup.Value) + input.Substring(captureGroup.Index + captureGroup.Length);
}

Console.WriteLine(input);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多