2017-10-13 50 views
0

我使用以下命令來執行存儲過程,但刪除不會運行。問題是什麼?刪除在存儲過程中不起作用

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 
+1

不給程序 「以sp_」 前綴http://sqlperformance.com/2012/10/t-sql-queries/sp_prefix – GuidoG

+0

這裏https://開頭MSDN .microsoft.com/en-us/library/ms190669(v = sql.105).aspx#命名%20Stored%20過程 – GuidoG

+2

SQL Server不支持宏替換...(@weight)中的權重) –

回答

3

讓它動態:

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 

,並把它作爲[更新與評論在線]

exec sp_delete 'fruits', '1.5,3.5' 
+0

爲什麼這與已經有所不同?您需要將逗號分隔值拆分爲表格。 –

+0

@WEI_DBA這有效。只是不要傳遞多餘的單引號,例如:exec sp_delete'fruits','1.5,3.5' – cloudsafe

+0

@cloudsafe Query在DELETE語句之前不需要檢查IF EXISTS,因爲如果沒有,DELETE將不會刪除任何行。否則,查詢必須將其刪除。出於同樣的原因,TRY CATCH在這裏也不是必需的。 – Amit