sql - MSSQL stored procedure select all columns -


i have stored procedure select statement looks this:

select @keyname dbo.ficonfig (nolock) issuerkey = @issuerkey 

where i'm creating this:

create procedure get_ficonfig    @issuerkey int,    @keyname nvarchar(100) 

where keyname column name retrieving data from.

my question: possible pass in * select columns although procedure asking specific column name?

edit: unfortunately think may have worded question poorly. looking way see if stored procedure tell if wanted select records table, or specific columns record. i've solved own problem using null checks , if/else statements.

you can use dynamic query:

create procedure get_ficonfig    @issuerkey int,    @keyname nvarchar(100) declare @s varchar(500) = 'select ' + @keyname + ' dbo.ficonfig (nolock) issuerkey = ' + cast(@issuerkey varchar(10)) exec(@s) 

you should careful here. possible sql injection. can not pass column names parameters dynamic query, there no other way.

but can select information_schema.columns table sure valid column name passed:

if exists(select * information_schema.columns            table_name = 'ficonfig' , column_name = @keyname) begin     declare @s varchar(500) = 'select ' + @keyname + ' dbo.ficonfig (nolock) issuerkey = ' + cast(@issuerkey varchar(10))     exec(@s) end else     throw... 

edit:

as user @lamak said better use quotename function. automatically add brackets around value of variable:

create procedure get_ficonfig    @issuerkey int,    @keyname nvarchar(100) declare @s varchar(500) = 'select ' + quotename(@keyname) + ' dbo.ficonfig (nolock) issuerkey = ' + cast(@issuerkey varchar(10)) exec(@s) 

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - Bypass Geo Redirect for specific directories -

php - .htaccess mod_rewrite for dynamic url which has domain names -