简体   繁体   中英

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. 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:

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".

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. If the expression

@ID, A, B, C

means the value of a parameter for the procedure EXEC SOME_OTHER_STORED_PROC, then declare the parameter like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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