我正在尝试将参数传递给查询,但是将引号作为字符串值。 但是我似乎可以使它工作。 我在这里做错什么了。
SqlConnection conn = new SqlConnection(SERP_FT_connection);
SqlCommand cmd = new SqlCommand("SELECT sp.* "
+ " FROM [serp_post] sp "
+ " LEFT JOIN [serp_m3_data] m3 ON m3.serp_post_id = sp.serp_post_id "
+ " WHERE sp.[serp_status_id]='CLEAR_DONE' AND sp.m3UpdateStatus <> '2' AND sp.process_type='POST' AND m3.EGTRCD = '40' AND m3.EPPYME = @paymentTerm ", conn);
cmd.CommandType = CommandType.Text;
conn.Open();
SqlParameter param = new SqlParameter();
param.ParameterName = "@paymentTerm";
param.Value = paymentTerm; // when debugged here it shows as "CH1"
cmd.Parameters.Add(param);
调试后查询如下:
SELECT sp.* FROM [serp_post] sp LEFT JOIN [serp_m3_data] m3 ON m3.serp_post_id = sp.serp_post_id WHERE sp.[serp_status_id]='CLEAR_DONE' AND sp.m3UpdateStatus <> '2' AND sp.process_type='POST' AND m3.EGTRCD = '40' AND m3.EPPYME = @paymentTerm
最后,查询应该看起来像是用引号引起来的值
SELECT sp.* FROM [serp_post] sp LEFT JOIN [serp_m3_data] m3 ON m3.serp_post_id = sp.serp_post_id WHERE sp.[serp_status_id]='CLEAR_DONE' AND sp.m3UpdateStatus <> '2' AND sp.process_type='POST' AND m3.EGTRCD = '40' AND m3.EPPYME = 'CH1'
答案 0 :(得分:1)
尝试在事件探查器中捕获参数化查询。正确的查询看起来像
exec sp_executesql N' SET FMTONLY OFF; SET NO_BROWSETABLE ON;SELECT sp.* FROM [serp_post] sp LEFT JOIN [serp_m3_data] m3 ON m3.serp_post_id = sp.serp_post_id WHERE sp.[serp_status_id]='CLEAR_DONE' AND sp.m3UpdateStatus <> '2' AND sp.process_type='POST' AND m3.EGTRCD = '40' AND m3.EPPYME = @paymentTerm',N'@paymentTerm varchar(10)',@paymentTerm='CH1'
如Jon Skeet所说,SQL参数未插入查询中。
答案 1 :(得分:0)
除了实际显示的注释以外,在发布期间会自动处理参数,而不是查询中的LITERAL,以防止sql-injection。
关于双引号的其他答案,我已经养成了以下示例中用C#编写sql的习惯,以帮助防止意外使用双引号。
SqlCommand cmd = new SqlCommand( "", conn);
cmd.CommandText =
@"SELECT
sp.*
FROM
[serp_post] sp
LEFT JOIN [serp_m3_data] m3
ON m3.serp_post_id = sp.serp_post_id
WHERE
sp.[serp_status_id]='CLEAR_DONE'
AND sp.m3UpdateStatus <> '2'
AND sp.process_type='POST'
AND m3.EGTRCD = '40'
AND m3.EPPYME = @paymentTerm ";
请注意完全可读的查询,而无需滚动或忘记下一行的双引号+,等等。同样,构建sql命令只是一种样式。前导@表示整个文本,直到将其用其他双引号引起来为止。由于SQL会忽略语句中的输入键,因此它们仍然可以正常工作并提高可读性。