简体   繁体   中英

SQL Stored Procedure with column name as variable

I really think this is a simple fix, but I didn't find any solution on the Internet (at least none I could understand).

I have this stored procedure:

ALTER PROC [dbo].[GetCard](
    @Input varchar(50),
    @Input2 varchar(50)
)
AS
SELECT * FROM Main WHERE @Input = @Input2;

But when I go:

GetCard 'CardName', 'Text';

SQL doesn't quite understand that @Input is a column. What do I have to change? Does it need any special syntax?

Build your query string like so (think I've got the single quotes right), and execute it:

SET @qString = 'SELECT * FROM MAIN WHERE ' + QuoteName(@Input) + ' = ''' + @Input2 + ''''

exec(@qString)

Simple fiddle demo

As Roman pointed out, be exceedingly careful with dynamic sql. Read up on SQL injection.

It is better to use dymamic SQL as Andrew or Roman Czerwinski recommended. But if you don't want to use dynamic SQL then you can use this logic:

ALTER PROC [dbo].[GetCard](
    @Input varchar(50),
    @Input2 varchar(50)
)
AS
SELECT * 
FROM Main 
WHERE CardName  = case when @Input = 'CardName'    then @Input2 else CardName    end
and OtherColumn = case when @Input = 'OtherColumn' then @Input2 else OtherColumn end
--etc...

In your code sample there is no column or parameter or variable with the name @Input1.

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