T-SQL SP动态删除

时间:2015-12-08 09:13:53

标签: sql-server tsql stored-procedures

我想编写SP以根据ID列从给定表中删除行。我尝试了以下方法:

CREATE PROCEDURE dbo.delResTab @schema VARCHAR(20), @table VARCHAR(50), @tableID int

AS

    DECLARE @column VARCHAR(50) = (
                              SELECT COLUMN_NAME
                              FROM INFORMATION_SCHEMA.columns
                              WHERE TABLE_SCHEMA = @schema
                              AND TABLE_NAME = @table
                              AND ORDINAL_POSITION = 1
                            )

    DELETE FROM @schema + '.' + @table WHERE @column >= @tableId

但这显然不起作用。有什么建议吗?

我希望能够运行

exec dbo.delResTab @schema = 'dbo', @table = 'test', @tableID = 3

1 个答案:

答案 0 :(得分:1)

CREATE PROCEDURE dbo.delResTab
(
    @schema SYSNAME,
    @table SYSNAME,
    @tableID INT
)
AS BEGIN

    SET NOCOUNT ON;

    DECLARE @SQL NVARCHAR(MAX)
    SELECT @SQL = '
        DELETE FROM [' + @schema + '].[' + @table + ']
        WHERE ' + c.name + ' >= ' + CAST(@tableID AS NVARCHAR(10))
    FROM sys.columns c
    WHERE c.is_identity = 1
        AND c.[object_id] = OBJECT_ID(@schema + '.' + @table)

    --PRINT @SQL
    EXEC sys.sp_executesql @SQL

END