[英]SQL query with c# stringbuilder error near “=” symbol
I'm working on some code that creates procedures with C#. 我正在研究一些使用C#创建过程的代码。 When I try to run my code:
当我尝试运行代码时:
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();
}
This part doesn't work . 这部分不起作用 。 It throws an exception:
它引发异常:
System.Data.SqlClient.SqlException: 'Incorrect syntax near '='.'
System.Data.SqlClient.SqlException:''='附近的语法不正确。
But when I try to run this part: 但是当我尝试运行此部分时:
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();
}
it runs correctly. 它可以正常运行。
Where is my mistake in the first snippet of code? 我在第一段代码中的错误在哪里?
Without sbSP1
final text it's difficult to pin down the error; 没有
sbSP1
最终文本 ,很难确定错误。 as a working hypothesis I suggest that PK
being complex (eg "id value"
) should be escaped - [PK]
. 作为一个工作假设我建议
PK
复杂(例如:正在"id value"
)应该被转义 - [PK]
In order to avoid such kind of errors, please, never build the query, but make procedure's text being readable with a help of string interpolation - $
and verbatim strings - @
. 为了避免此类错误,请不要构建查询,而应借助字符串插值 -
$
和逐字字符串 - @
使过程的文本 可读 。
//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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.