简体   繁体   English

在通过C#调用的动态查询中转义'@'符号

[英]Escaping the '@' Symbol in a dynamic query called through C#

I've got a simple console app at the moment that calls a stored procedure with a few parameters and creates a dynamic query and executes it. 我现在有一个简单的控制台应用程序,它调用带有一些参数的存储过程并创建一个动态查询并执行它。 However, in the dynamic query i'll need to pass a value that contains the '@' symbol. 但是,在动态查询中,我需要传递一个包含“@”符号的值。 For example in the @Query parameter I need to pass a value that contains the '@' symbol. 例如,在@Query参数中,我需要传递一个包含'@'符号的值。 This is dynamic so the value may not contain this in the future: 这是动态的,因此未来可能不包含此值:

SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "STORED PROCEDURE";

cmd.Parameters.Add(new SqlParameter() { ParameterName = "@Query", Value = "@ID, A, B, C", SqlDbType = SqlDbType.VarChar });
cmd.Parameters.Add(new SqlParameter() { ParameterName = "@Database", Value = "XXXX", SqlDbType = SqlDbType.VarChar });
cmd.Parameters.Add(new SqlParameter() { ParameterName = "@Server", Value = "YYYY", SqlDbType = SqlDbType.VarChar });
ocmd.Parameters.Add(new SqlParameter() { ParameterName = "@TableName", Value = "TESTTABLE", SqlDbType = SqlDbType.VarChar });
....
....
....
cmd.ExecuteScalar();

Then on the Sql Server end, I piece these parameters together so that it looks as such: 然后在Sql Server端,我将这些参数拼凑在一起,使它看起来像这样:

SET @SQLQuery  = 'INSERT INTO ' + convert(varchar(500),@TableName)  + ' EXEC SOME_OTHER_STORED_PROC ' 
                    + convert(varchar(500),@Query) + ', ' 
                    + convert(varchar(500),@Database) + ', ' 
                    + convert(varchar(500),@Server) 
    EXECUTE sp_executesql @SQLQuery

Every time I run this I get the following error Must declare the scalar variable "@ID". 每次我运行这个我得到以下错误必须声明标量变量“@ID”。

Any help is appreciated, Thanks! 任何帮助表示赞赏,谢谢!

I don't think that problem is the @ character. 我不认为问题是@字符。 As you have defined the query, the @ID is considered as parameter, which is not defined anywhere. 由于您已定义查询,因此@ID被视为参数,该参数未在任何位置定义。 If the expression 如果表达

@ID, A, B, C @ ID,A,B,C

means the value of a parameter for the procedure EXEC SOME_OTHER_STORED_PROC, then declare the parameter like: 表示过程EXEC SOME_OTHER_STORED_PROC的参数值,然后声明参数如:

cmd.Parameters.Add(new SqlParameter() { ParameterName = "@Query", Value = "'@ID, A, B, C'", SqlDbType = SqlDbType.VarChar });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM