如何在SQL Server 2008中截断选择性表, 我有一个表格列表,可以在截断过程中排除。
有人可以指导我吗?
答案 0 :(得分:2)
您只需运行TRUNCATE TABLE yourTableName
即可。如果您有列表,则可以运行以下命令:
CREATE TABLE #truncateTables(name nvarchar(255))
INSERT INTO #truncateTables(name) VALUES(N'dbo.yourTable1'),(N'dbo.yourTable2')
DECLARE cur CURSOR FOR
SELECT name FROM #truncateTables
OPEN cur
DECLARE @sql nvarchar(max), @tabname nvarchar(255)
FETCH NEXT FROM cur INTO @tabname
WHILE @@FETCH_STATUS = 0 BEGIN
SET @sql = N'TRUNCATE TABLE '+@tabname
BEGIN TRY EXEC(@sql)
END TRY
BEGIN CATCH -- if a foreign key constraint exists
SET @sql = N'DELETE FROM '+@tabname
EXEC(@sql)
END CATCH
FETCH NEXT FROM cur INTO @tabname
END
CLOSE cur
DEALLOCATE cur
DROP TABLE #truncateTables