将列名动态传递给SQL查询

时间:2015-02-25 21:44:25

标签: sql sql-server tsql stored-procedures dynamic-sql

我想知道是否可以传递表的列名,以便我可以为我的存储过程创建动态查询。我将不胜感激任何帮助!

好查询:

SELECT
A1,
LEFT (A1,CHARINDEX(',',A1)-1) AS UPC,
SUBSTRING(A1,CHARINDEX(',', A1 , 1)  + 1,LEN(A1) - CHARINDEX(',', A1) - CHARINDEX(',', REVERSE(A1))) AS Date,
SUBSTRING(A1,CHARINDEX(',', A1 , 1)  + 7,LEN(A1) - CHARINDEX(',', A1) - CHARINDEX(',', REVERSE(A1))) AS Qty
FROM Registry Where Id=26

输出:

 A1              UPC      Date    Qty
-------------------------------------
CPU1,01/15,3     CPU1     01/15   3

这是我到目前为止的存储过程

SP:

ALTER PROCEDURE [dbo].[SP_UPD_Compartment] 
@Id  int, 
@Col_Name char(40) 

AS
BEGIN
SET NOCOUNT ON;

SELECT
@Col_Name,
LEFT (@Col_Name,CHARINDEX(',',@Col_Name)-1) AS UPC,
SUBSTRING(@Col_Name,CHARINDEX(',', @Col_Name , 1)  + 1,LEN(@Col_Name) - CHARINDEX(',', @Col_Name) - CHARINDEX(',', REVERSE(@Col_Name))) AS Date,
SUBSTRING(@Col_Name,CHARINDEX(',', @Col_Name , 1)  + 7,LEN(@Col_Name) - CHARINDEX(',', @Col_Name) - CHARINDEX(',', REVERSE(@Col_Name))) AS Qty
FROM Registry Where Id=@Id

END

错误消息:

Msg 537, Level 16, State 2, Procedure SP_UPD_Compartment, Line 9
Invalid length parameter passed to the LEFT or SUBSTRING function.

1 个答案:

答案 0 :(得分:1)

我正在从标签键入,因此可能存在一些语法错误,但我认为您会明白这一点。首先,使用语句创建一个字符串,然后将子串“@Col_Name”替换为带有传递参数的过程。然后你执行那个动态的sql。您还可以在Print @cmd之前添加EXEC(@cmd),以查看实际执行的内容。

ALTER PROCEDURE [dbo].[SP_UPD_Compartment] 
@Id  INT, 
@Col_Name CHAR(40) 

AS
BEGIN
SET NOCOUNT ON;

DECLARE @cmd NVARCHAR(4000) =
'SELECT
@Col_Name,
LEFT (@Col_Name,CHARINDEX('','',@Col_Name)-1) AS UPC,
SUBSTRING(@Col_Name,CHARINDEX('','', @Col_Name , 1)  + 1,LEN(@Col_Name) - CHARINDEX('','', @Col_Name) - CHARINDEX('','', REVERSE(@Col_Name))) AS Date,
SUBSTRING(@Col_Name,CHARINDEX('','', @Col_Name , 1)  + 7,LEN(@Col_Name) - CHARINDEX('','', @Col_Name) - CHARINDEX('','', REVERSE(@Col_Name))) AS Qty
FROM Registry WHERE Id=' + CAST(@Id AS NVARCHAR(20))

SET @cmd = REPLACE(@cmd, '@Col_Name', @Col_Name)
EXEC(@cmd)

END