简体   繁体   English

IF-THEN-ELSE:创建/截断表-SQL Server

[英]IF-THEN-ELSE: Create / Truncate Table - SQL Server

I am attempting to create a backup table without having to re-create it every single time. 我试图创建一个备份表,而不必每次都重新创建它。 If the table already exists in the next run then it should simply truncate the table. 如果该表在下一次运行中已经存在,则应简单地截断该表。

But it doesn't seem to be working. 但这似乎不起作用。 It says backup_reportsettings is already in the database. 它说backup_reportsettings已经在数据库中。 Can anyone assist me with this? 有人可以协助我吗?

--Only re-create table if table does not exist otherwise truncate the existing table.   
IF NOT EXISTS (SELECT * FROM [Misc].sys.tables where name= 'dbo.backup_reportsettings')
    CREATE TABLE [MISC].dbo.backup_reportsettings 
    (
        [datestamp] [datetime] NULL,
        [reportsettingid] [char](8) NOT NULL,
        [description] [char](30) NOT NULL,
        [formname] [char](30) NOT NULL,
        [usersid] [char](8) NOT NULL,
        [settings] [text] NOT NULL,
        [notes] [varchar](255) NOT NULL,
        [userdefault] [char](1) NOT NULL
    )
ELSE 
    TRUNCATE TABLE [Misc].dbo.backup_reportsettings;

What am I doing wrong? 我究竟做错了什么? Note: this is done within a transaction. 注意:这是在交易中完成的。

Object names in sys.tables don't have the schema as part of the name. sys.tables对象名称不包含架构。 Remove the table schema when verifying whether the table exists: 在验证表是否存在时删除表架构:

IF NOT EXISTS (SELECT * FROM [Misc].sys.tables where name= 'backup_reportsettings')

Despite the use of IF , SQL Server needs to Parse/Compile all the statements in your script, so when it sees a CREATE TABLE statement it will give you a compilation error if the table already exists, even though the IF would prevent that code from being executed when that is the case. 尽管使用了IF ,SQL Server仍需要解析/编译脚本中的所有语句,因此,当看到CREATE TABLE语句时,即使该表已存在,它也会给您一个编译错误,即使IF会阻止该代码从在这种情况下被执行。

The way to get around this is to put your CREATE TABLE statement in dynamic SQL, which will not be parsed/compiled before execution. 解决此问题的方法是将您的CREATE TABLE语句放入动态SQL中,该语句在执行前不会被解析/编译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM