Delete using case statement in SQL Server 2008
I want to delete rows on the basis of their id. For multiple tables I want to generate a single query that will accept the table name and id and perform the operation.
Now the scenario is that, I don't 开发者_如何学Gowant to use if - else statement. I want to use case statement to detect the table name perform the function.
Please help me.
As been mentioned by Martin, you can't directly but you could write a stored procedure to perform the delete.
Comparing
EXEC SLOW_DELETE 'TestTable', 1
with
DELETE FROM TestTable WHERE ID = 1
is not a huge difference though (besides being a performance drain).
Stored Procedure
CREATE PROCEDURE SLOW_DELETE(@TableName sysname, @ID INT) AS
BEGIN
IF ((SELECT COUNT(*) FROM sys.tables WHERE name=@TableName) <> 1)
BEGIN
RAISERROR('Ambiguous or non existent table name passed %s',16,1,@TableName)
RETURN
END
DECLARE @Stmt nvarchar(500)
SET @Stmt = 'DELETE FROM ' + QUOTENAME(@TableName) + ' WHERE ID = @ID'
EXEC sp_executesql @Stmt, N'@ID INT', @ID = @ID
END
I wonder what you hope to gain from using such an approach. Perhaps if you expand on your motives, we could suggest an alternative approach.
精彩评论