0

I used the following command to execute the stored procedure, but the delete wont run. what is the problem?

exec sp_delete 'fruits', '''1.5'',''3.5'''

sp_delete

CREATE PROCEDURE [dbo].[sp_delete] 
@stock_type VARCHAR(255) 
,@weight VARCHAR(255)

AS 

IF @stock_type ='fruits'
BEGIN TRY
IF EXISTS(SELECT * FROM tblshop WHERE quantity='1' and weight in ( @weight))
    BEGIN
        DELETE FROM tblshop WHERE quantity='1' and weight in ( @weight )
    END
END TRY
BEGIN CATCH
END CATCH
12
  • 1
    dont give procedures"sp_" as prefix sqlperformance.com/2012/10/t-sql-queries/sp_prefix Commented Oct 13, 2017 at 14:49
  • 2
    SQL Server does not support macro substitution ... weight in ( @weight)) Commented Oct 13, 2017 at 14:50
  • 1
    Also there is no need to first check if it exists an than delete it. Only records that exists will be deleted anyway. Commented Oct 13, 2017 at 14:52
  • 1
    You need to pass the different values as an array to the procedure, look at this example stackoverflow.com/questions/11102358/… Commented Oct 13, 2017 at 14:53
  • 1
    @whoami Was stock_type 'fruits' or 'AC' Commented Oct 13, 2017 at 14:55

2 Answers 2

3

Make it dynamic:

CREATE PROCEDURE [dbo].[sp_delete] 
@stock_type VARCHAR(255) 
,@weight VARCHAR(255)
AS 
declare @sql as nvarchar(max)
IF @stock_type ='fruits'
BEGIN TRY
set @sql = '
IF EXISTS(SELECT * FROM tblshop WHERE quantity=''1'' and weight in ( ' + @weight + '))
    BEGIN
        DELETE FROM tblshop WHERE quantity=''1'' and weight in ( ' + @weight + ' )
    END'
exec(@sql)
END TRY
BEGIN CATCH
END CATCH

and call it as [Update inline with comments]

exec sp_delete 'fruits', '1.5,3.5'
Sign up to request clarification or add additional context in comments.

4 Comments

Why is this different from what they have already? You need to split the comma separated values into a table.
@WEI_DBA This works. Just don't pass the superfluous single quotes i.e: exec sp_delete 'fruits', '1.5,3.5'
@cloudsafe Query need not check IF EXISTS before DELETE statement, because DELETE will not delete any row if there is none. Otherwise, query has to delete it anyways. For the same reason, TRY CATCH is also not required here.
@cloudsafe. Ah. Didn't see the parms passing in. Thanks!
1

You need to split @weight value into an array-like

and then WHERE quantity='1' and weight in dbo.splitFunc(@weight)

How to pass an array into a SQL Server stored procedure

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.