如何检查表是否为空,如果是,删除SQL Server 2008中的所有行?

时间:2014-12-01 20:56:09

标签: sql-server sql-server-2008

我在Microsoft SQL Server Management Studio 2008中编写了一系列SQL插入语句。我的问题是:如何检查现有表是否有任何行,如果是,则删除所有行,然后继续插入陈述?

基本上,我正在寻找能够做到这一点的声明:

如果“greek_organizations”有数据 删除所有行

感谢您的帮助!

7 个答案:

答案 0 :(得分:3)

您可以使用EXISTS来检查:

IF EXISTS (SELECT * FROM [table])
    BEGIN
        DELETE FROM [table]
        ---Or for fast delete use:  TRUNCATE TABLE [table]
    END
ELSE
    BEGIN
        PRINT 'nothing in table'
    END

答案 1 :(得分:2)

我同意以前的海报。表的结果状态将始终为空。所以你应该总是截断表... Obs,我会检查以确保表在Truncating之前存在 但这是真正的解决方案:

if OBJECT_ID(N'Test', N'U') is not null
    Truncate Table Test;

回答你的问题:

if (select count(1) from Test) > 0
begin
    Truncate Table Test;
End

答案 2 :(得分:1)

If exists(select * from  [greek_organizations] )
begin
delete from [greek_organizations]
end
else
begin
insert...
end

答案 3 :(得分:0)

IF (SELECT COUNT(*) FROM greek_organizations) > 0
BEGIN
DELETE FROM greek_organizations
END

答案 4 :(得分:0)

为什么检查表格是否有任何记录?您可以编写一个删除查询,在查询插入之前删除所有记录。

答案 5 :(得分:0)

检查行数的更快方法就像......

IF EXISTS(SELECT 1 FROM sys.dm_db_partition_stats
                  WHERE Object_Name(Object_Id) = 'TableName')
BEGIN
  -- DELETE FROM TableName
  -- OR
  -- TRUNCATE TABLE TableName
END

答案 6 :(得分:0)

delete greek_organizations;  
insert into greek_organizations (desc) values ('one'), ('two'), ('three');

delete greek_organizations;
insert into greek_organizations (desc) 
select desc 
from staging_table;