Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass column name as input parameter in SQL stored Procedure

create procedure sp_First
@columnname varchar
AS
begin
select @columnname from Table_1
end 
exec sp_First 'sname'

My requirement is to pass column names as input parameters. I tried like that but it gave wrong output.

So Help me

like image 519
user1169809 Avatar asked Apr 10 '12 16:04

user1169809


People also ask

How do you pass a list of values to a parameter of a stored procedure?

CREATE FUNCTION dbo. SplitInts ( @List VARCHAR(MAX), @Delimiter VARCHAR(255) ) RETURNS TABLE AS RETURN ( SELECT Item = CONVERT(INT, Item) FROM ( SELECT Item = x.i.value('(./text())[1]', 'varchar(max)') FROM ( SELECT [XML] = CONVERT(XML, '<i>' + REPLACE(@List, @Delimiter, '</i><i>') + '</i>'). query('.

Can pass 3 types of parameters to stored procedures What are they?

As a program, a stored procedure can take parameters. There are three types of parameters: IN, OUT and INOUT.


2 Answers

You can do this in a couple of ways.

One, is to build up the query yourself and execute it.

SET @sql = 'SELECT ' + @columnName + ' FROM yourTable'
sp_executesql @sql

If you opt for that method, be very certain to santise your input. Even if you know your application will only give 'real' column names, what if some-one finds a crack in your security and is able to execute the SP directly? Then they can execute just about anything they like. With dynamic SQL, always, always, validate the parameters.

Alternatively, you can write a CASE statement...

SELECT
  CASE @columnName
    WHEN 'Col1' THEN Col1
    WHEN 'Col2' THEN Col2
                ELSE NULL
  END as selectedColumn
FROM
  yourTable

This is a bit more long winded, but a whole lot more secure.

like image 79
MatBailie Avatar answered Oct 17 '22 04:10

MatBailie


No. That would just select the parameter value. You would need to use dynamic sql.

In your procedure you would have the following:

DECLARE @sql nvarchar(max) = 'SELECT ' + @columnname + ' FROM Table_1';
exec sp_executesql @sql, N''
like image 13
Darren Kopp Avatar answered Oct 17 '22 05:10

Darren Kopp