0

I have a SQL query stored in a table that contains parameter names. I need to know how to execute it properly in a stored procedure.

This is my SQL code in the procedure

PROCEDURE [spMassUpdateSKUs]
@SKU AS NVARCHAR(20)
,@FIELD AS NVARCHAR(50)
,@VALUE AS NVARCHAR(50)
,@RESULT as Int = Null Output
AS
BEGIN
IF EXISTS(SELECT CODENUMBER FROM INVENTORY_MASTER WHERE CODENUMBER=@SKU)
    BEGIN   
    DECLARE @SQLQUERY AS NVARCHAR(50)
    SET @SQLQUERY=(SELECT SQLUPDATE FROM MASS_UPDATE WHERE DROPDOWNLABEL=@FIELD)
    EXEC SP_EXECUTESQL @SQLQUERY
    END

and this is the sql query from the table

update inventory_master_flex set departmentid=@value where codenumber=@sku

I've tried replacing with the real parameters but that doen't work.

SELECT REPLACE(REPLACE(@SQLQUERY,'@VALUE',@VALUE),'@SKU',@SKU)
3
  • When you executed this SELECT REPLACE(REPLACE(@SQLQUERY,'@VALUE',@VALUE),'@SKU',@SKU) what did the update query look like? Did it look correct or not? What do you mean it doesn't work? If departmentid and codenumber are strings you need single quotes around them. Commented Dec 12, 2016 at 20:05
  • The capitalization is different. By default, SQL Server is case-insensitive, but your table, database, or server might be configured differently. Commented Dec 12, 2016 at 20:05
  • Your values won't be quoted with your current REPLACE code. You should pass the parameters properly though, using sp_executesql Commented Dec 12, 2016 at 20:07

2 Answers 2

1
-- 50 is too short for sure; you may try 1000 or different number
DECLARE @SQLQUERY AS NVARCHAR(MAX)

-- for debug purpose
PRINT @SQLQUERY

-- params
EXEC SP_EXECUTESQL @SQLQUERY, N'@Value NVARCHAR(50), @sku NVARCHAR(50)`, @Value, @sku

REPLACE is not good in case of strings with quotes and so on which would brake the @sqlquery code.

Sign up to request clarification or add additional context in comments.

Comments

1

Pass the parameters in using sp_executesql, not replace():

IF EXISTS(SELECT CODENUMBER FROM INVENTORY_MASTER WHERE CODENUMBER=@SKU)
    BEGIN   
        DECLARE @SQLQUERY AS NVARCHAR(MAX);

        SET @SQLQUERY = (SELECT SQLUPDATE FROM MASS_UPDATE WHERE DROPDOWNLABEL = @FIELD);

        EXEC SP_EXECUTESQL @SQLQUERY, N'@SKU VARCHAR(255), @VALUE VARCHAR(255)', @SKU = @SKU, @VALUE = @VALUE
    END;

I don't know what the types are. But if one or both are strings or dates, then you would need single quotes in your implementation. However, you are already using sp_executesql so go whole-hog and pass in parameters as well.

Comments

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.