0

I have a comma delimited string with column names i.e.

"Column1, Column2, Column3" which will be passed as a parameter to the following stored procedure.

My Stored Procedure is as follows:

@ColNames VARCHAR(1000)

Select ROW_NUMBER() OVER (ORDER BY Column1, Column2, Column3) AS RowNum, 
Column1, Column2, Column3
INTO #Results
From Table A 

I want to replace the above hardcoded column names with the parameter @colNames. This will include splitting the comma delimited parameter into the individual column names.

1

2 Answers 2

2

You'd need to use dynamic SQL in this case and execute it with sp_executesql.
For example:

DECLARE @ColNames VARCHAR(1000)
DECLARE @sSQL NVARCHAR(MAX)

SET @ColNames ='Column1, Column2,...'

SET @sSQL = 'SELECT ' + @ColNames + ' FROM myTable....'

exec sp_executesql @sSQL



I also made a quick SQLFiddle to this.

Sign up to request clarification or add additional context in comments.

3 Comments

This is not correct, sql server will treat this passed string of column names as a string but not object names.
You don't need to pass @ColNames to that sp_executesql: the value is already embedded in @sSQL
@M.Ali Could you point out exactly what would be not working out? Testing this out really quick @SQLFiddle seems to work.
2

You may try this :

CREATE PROCEDURE yourId (@columns VARCHAR(1000))
AS
BEGIN
DECLARE @s_query VARCHAR(MAX)

SET @s_query = 'Select ROW_NUMBER() OVER (ORDER BY ' + @columns + ') AS RowNum, ' + @columns + ' From A'

EXEC(@s_query)
END

this is for t sql syntax

If you need information on how to split a string, you may have a look on this thread : Split function equivalent in T-SQL?

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.