开发者

Delete using case statement in SQL Server 2008

开发者 https://www.devze.com 2023-02-05 10:56 出处:网络
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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号