C# c“stringbuilder错误接近”的SQL查询=&引用;符号
我正在编写一些用C#创建过程的代码。当我尝试运行代码时:C# c“stringbuilder错误接近”的SQL查询=&引用;符号,c#,sql-server,runtime-error,C#,Sql Server,Runtime Error,我正在编写一些用C#创建过程的代码。当我尝试运行代码时: StringBuilder sbSP1 = new StringBuilder(); sbSP1.AppendLine("CREATE PROCEDURE " + ProcN + "DELETE @id int=0 AS BEGIN DELETE FROM " + tname + " WHERE " + PK + " = @id END"); SqlConnection connection = new SqlConnection(c
StringBuilder sbSP1 = new StringBuilder();
sbSP1.AppendLine("CREATE PROCEDURE " + ProcN + "DELETE @id int=0 AS BEGIN DELETE FROM " + tname + " WHERE " + PK + " = @id END");
SqlConnection connection = new SqlConnection(connectionString);
using (SqlCommand cmd = new SqlCommand(sbSP1.ToString(), connection))
{
connection.Open();
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
connection.Close();
}
这部分不行。它抛出一个异常:
System.Data.SqlClient.SqlException:“=”附近的语法不正确。”
但当我尝试运行此部件时:
StringBuilder sbSP3 = new StringBuilder();
sbSP3.AppendLine("CREATE PROCEDURE " + ProcN + "GET AS BEGIN SET NOCOUNT ON; SELECT " + columns + " from " + tname + " END");
SqlConnection connection = new SqlConnection(connectionString);
using (SqlCommand cmd = new SqlCommand(sbSP3.ToString(), connection))
{
connection.Open();
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
connection.Close();
}
它运行正常
我在第一段代码中的错误在哪里?没有
sbSP1
最终文本,很难确定错误;作为一个工作假设,我认为PK
是复杂的(例如“id-value”
)
应该转义-[PK]
。为了避免此类错误,请不要构建查询,而是借助字符串插值-$
和逐字字符串-@
使过程文本可读
//TODO: check the text, is it the procedure you want to create?
string text =
$@"create procedure [{ProcN}Delete]
@id int = 0 as
begin
delete
from [{tname}]
where [{PK}] = @id
end;";
//DONE: do not close connection manually, but wrap it into using
using (SqlConnection connection = new SqlConnection(connectionString)) {
connection.Open();
using (qlCommand cmd = new SqlCommand(text, connection)) {
cmd.ExecuteNonQuery();
}
}
没有
sbSP1
final text,就很难确定错误;作为一个工作假设,我认为PK
是复杂的(例如“id-value”
)
应该转义-[PK]
。为了避免此类错误,请不要构建查询,而是借助字符串插值-$
和逐字字符串-@
使过程文本可读
//TODO: check the text, is it the procedure you want to create?
string text =
$@"create procedure [{ProcN}Delete]
@id int = 0 as
begin
delete
from [{tname}]
where [{PK}] = @id
end;";
//DONE: do not close connection manually, but wrap it into using
using (SqlConnection connection = new SqlConnection(connectionString)) {
connection.Open();
using (qlCommand cmd = new SqlCommand(text, connection)) {
cmd.ExecuteNonQuery();
}
}
我建议查看结果查询文本。那么问题应该很明显了。@Afonso。。。UH甚至对于创建存储过程的查询?我认为这不太好。sbSP1.ToString()的确切值是多少?@Afonso SQL Server不支持类似的内容。你不能做
创建过程@ProcName AS…
,你只会得到一个语法错误。我真的建议你按照@mjwills的建议去做,并在你将它分配给SqlCommand
时包含sbSP1.ToString()的确切值,但我最初的预感是ProcN
或PK
包含一个空格,或者一些无效字符。我建议查看结果查询文本。那么问题应该很明显了。@Afonso。。。UH甚至对于创建存储过程的查询?我认为这不太好。sbSP1.ToString()的确切值是多少?@Afonso SQL Server不支持类似的内容。你不能做创建过程@ProcName AS…
,你只会得到一个语法错误。我真的建议你按照@mjwills的建议去做,并在你将它分配给SqlCommand
时包含sbSP1.ToString()的确切值,但我最初的预感是ProcN
或PK
包含一个空格,或者一些无效字符。