0

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.
1
  • Read a little about sp_executesql Commented Feb 25, 2015 at 22:01

1 Answer 1

1

I am typing from tab, so there may be some syntax mistakes, but i think you will get the idea. First you create a string with your statement and then replace substring '@Col_Name' with passed parameter to procedure. Then you execute that dynamic sql. You can also add Print @cmd before EXEC(@cmd) to see what actually will be executed.

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
Sign up to request clarification or add additional context in comments.

1 Comment

@Carlos, you could write directly 'Update Registry Set @Col_Name = LEFT (@Col_Name,CHARINDEX('','',@Col_Name)-1) + '','' + LEFT (@Col_Name,CHARINDEX('','',@Col_Name)-1)' . Now you don't need replace for comma.

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.