简体   繁体   English

如何将列的字符串数组作为参数传递给SQL Server存储过程

[英]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.

相关问题 如何将数组传递到 SQL 服务器存储过程 - How to pass an array into a SQL Server stored procedure 如何将3D数组传递给SQL Server存储过程 - How to pass a 3D array to a SQL Server stored procedure 将整数数组传递给SQL Server存储过程 - Pass integer array to the SQL Server stored procedure 如何将变量传递给 SQL 服务器存储过程? - How to pass a variable to SQL Server stored procedure? 如何将字符串数组传递给存储过程? - How to pass a string array like to stored procedure? 如何通过ADO.NET实体模型从C#将字符串数组传递到SQL Server中的存储过程中 - How to pass a string array into a stored procedure in SQL Server from c# via ADO.NET entity model 如何在SQL Server中将动态创建的筛选器作为存储过程的参数传递并筛选数据? - How to pass dynamically created filters as parameter of stored procedure in SQL Server and filter data? 如何在SQL Server中将列名和表名作为参数传递给存储过程? - How to pass column name as well as Table Name to a stored procedure as a parameter in SQL Server? 如何传递字符串列表的sql参数以删除存储过程? - How to pass a list of strings a sql parameter for the stored procedure to delete? 如何将C#中的byte []作为字符串传递到SQL Server存储过程并转换为varbinary(MAX) - How to pass byte[] from C# as string to SQL Server stored procedure and convert into varbinary(MAX)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM