[英]How create SQL Server stored procedure, keeping line breaks and tabs, from record stored in database with C#
SQL Server: I have copied and saved a stored procedure in a database. SQL Server:我在数据库中复制并保存了一个存储过程。 During that process, it has escaped the line feeds and tabs into \\n and \\t characters throughout the stored procedure text so it looks like:
在该过程中,它已将整个存储过程文本中的换行符和制表符转义为 \\n 和 \\t 字符,因此它看起来像:
SQL = "create PROCEDURE ScrambleNames\n\t@removeAdmins bit \nAS\nBEGIN\n\t-- SET NOCOUNT ON added to prevent..." just shortened for clarity
using (DbConnection dbcn = dbf.CreateConnection())
{
dbcn.ConnectionString = cnxn;
dbcn.Open();
using (DbCommand dbcmd = dbcn.CreateCommand())
{
dbcmd.CommandType = CommandType.Text;
dbcmd.CommandText = SQL;
dbcmd.ExecuteNonQuery();
}
}
I want to read that SQL statement with C# and use it to create an actual stored procedure in another database by executing that command.我想用 C# 读取该 SQL 语句,并使用它通过执行该命令在另一个数据库中创建一个实际的存储过程。 Obviously, when I try and execute it without any changes, it says there is a syntax error near \\ and fails.
显然,当我尝试在没有任何更改的情况下执行它时,它说 \\ 附近存在语法错误并且失败。 I've tried replacing the \\n and \\t with actual binary characters in the string but it fails with more errors:
我试过用字符串中的实际二进制字符替换 \\n 和 \\t ,但它失败并出现更多错误:
Incorrect syntax near '1'... etc.
'1' 附近的语法不正确...等。
So, how can I read the text from the database and keep the line feeds and tabs in the stored procedure I'm trying to create?那么,如何从数据库中读取文本并在我尝试创建的存储过程中保留换行符和制表符?
Use verbatim strings with @ to support multiline strings, like this使用带有@ 的逐字字符串来支持多行字符串,就像这样
SQL = @"create PROCEDURE ScrambleNames
@removeAdmins bit
AS BEGIN
-- comment here
SELECT * FROM";
using (DbConnection dbcn = dbf.CreateConnection())
{
dbcn.ConnectionString = cnxn;
dbcn.Open();
using (DbCommand dbcmd = dbcn.CreateCommand())
{
dbcmd.CommandType = CommandType.Text;
dbcmd.CommandText = SQL;
dbcmd.ExecuteNonQuery();
}
}
Example to explain verbatim string:解释逐字字符串的示例:
normal_string = "Line1 \n Line2 \n line3";
same_as_verbatim_string = @"Line1
Line2
line3";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.