1

I want to build a dynamic query where the column name and table name are paramaters.

The following is the code I have written:

List<SqlParameter> parametersList = new List<SqlParameter>();

SqlParameter param = new SqlParameter();
param.ParameterName = "param1";
param.SqlDbType = System.Data.SqlDbType.VarChar;
param.Value = parma1;
parametersList.Add(param);

param = new SqlParameter();
param.ParameterName = "param2";
param.SqlDbType = System.Data.SqlDbType.VarChar;
param.Value = param2;
parametersList.Add(param);

I have created two paramters, @param1 and @param2, which are passed to the function:

This gives me the following error:

"Invalid object name 'param1"

It seems that the parameter values are not being replaced while executing the command. What am I missing here?

1 Answer 1

1

You just need to tweak your SQL query string slightly as your parameters are a part of the string in SQL's eyes.

Change it to this and it should work:

string query = "DECLARE @sqlQuery varchar(max); " +
    " SELECT @sqlQuery = 'select distinct [' + @columnName + '] from [" +
         Globals.REPORTING_SCHEMA + "].[' + @tableName + ']'; " +
    " exec(@sqlQuery);";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.