I was wondering if is possible to pass the column name of a table so I can create a dynamic query for my stored procedure. I will appreciate any help!
Good query:
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
Output:
A1 UPC Date Qty
-------------------------------------
CPU1,01/15,3 CPU1 01/15 3
This is what I have so far for the stored procedure
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
Error msg:
Msg 537, Level 16, State 2, Procedure SP_UPD_Compartment, Line 9
Invalid length parameter passed to the LEFT or SUBSTRING function.