Monday, March 19, 2012

how to use parameter value as a column name

I am feeding in @.RsCategory varchar (25) into my stored procedure. I was hoping to make the RsCategory = the column name from the table I would like to select data from.

How can I use @.RscCategory as the column name value in the select statement? (or can I?)

select @.RsCategory as displaydata

From tTable T

where T.MyOtherParams=@.MyOtherParams

Any help would be greatly appreciated!

One way is to use dynamic SQL

DELCARE @.strSQL = 'SELECT ' + @.RsCategory + 'AS displaydata FROM tTable T WHERE MyOtherParam=' + @.MyOtherParams

EXEC @.strSQL

|||

You got the answer to your question. But what are you trying to do actually by sending the column name to be selected from client side? You can either write different SELECT statements in your SP or return the minimal data that you need and let the client hide the columns based on the configuration. Using dynamic SQL is simple but it has lot of security and maintainence issues. For example, the posted code doesn't protect against SQL injection attacks. You can do that by using QUOTENAME on the passed column name parameter.

An alternative approach is to use CASE expression as shown below which will work if the columns are compatible data types:

select case @.RscCategory

when 'Col1' then t.Col1

when 'Col2' then t.Col2

end as displaydata

No comments:

Post a Comment