[英]How to pass string array of Columns as parameter to SQL Server Stored procedure
I have a comma delimited string with column names ie 我有一个逗号分隔的字符串,列名称为
"Column1, Column2, Column3"
which will be passed as a parameter to the following stored procedure. "Column1, Column2, Column3"
将作为参数传递到以下存储过程。
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
. 我想用参数
@colNames
替换上面的硬编码列名。 This will include splitting the comma delimited parameter into the individual column names. 这将包括用逗号分隔的参数拆分为单独的列名称。
You'd need to use dynamic SQL in this case and execute it with sp_executesql . 在这种情况下,您需要使用动态SQL并使用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. 我对此也做了一个快速的SQLFiddle 。
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 这是用于t sql语法
If you need information on how to split a string, you may have a look on this thread : Split function equivalent in T-SQL? 如果您需要有关如何分割字符串的信息,可以在此线程上看看: 分割函数是否等效于T-SQL?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.