如果表存在则插入数据或创建表并插入数据

时间:2016-07-30 08:52:41

标签: sql sql-server visual-studio windows-services

我正在尝试通过Windows服务插入数据,我必须检查表是否存在,并插入数据(如果存在)。如果不存在,则创建表并在同一个表中插入数据...如果表不存在,我可以创建表并插入数据。但是如果表存在无法使用以下代码将数据插入表中...提前感谢....

  if not exists (select * from sysobjects where name='" + tablename + "' and  xtype='U') 

create table " + tablename + 
" (ID int IDENTITY(1,1) NOT NULL,Data nvarchar(max) NULL)  
Insert into " + tablename + " (Data) VALUES('" + Message + "') 

更新:   修改后,它与sql server工作正常但是当我尝试通过visual studio Console应用程序执行此操作时抛出异常!

2 个答案:

答案 0 :(得分:1)

您的代码正在检查它是否不存在,它是否创建并插入数据,但是您跳过了else部分 表存在的地方,那么你只插入数据

if not exists (select * from sysobjects where name='" + tablename + "' and      xtype='U') 

begin
create table " + tablename + 
" (ID int IDENTITY(1,1) NOT NULL,Data nvarchar(max) NULL)  
Insert into " + tablename + " (Data) VALUES('" + Message + "') 
End

ELSE
  Insert into " + tablename + " (Data) VALUES('" + Message + "')

或指定在此条件下该做什么的开始和结束

if not exists (select * from sysobjects where name='" + tablename + "' and      xtype='U') 

begin
create table " + tablename + 
" (ID int IDENTITY(1,1) NOT NULL,Data nvarchar(max) NULL)  
end 
Insert into " + tablename + " (Data) VALUES('" + Message + "') 

答案 1 :(得分:0)

对于这种问题,我将在T-SQL(MS SqlServer)中使用GOTO

IF EXISTS (select * from sysobjects where name='" + tablename + "' and xtype='U')
     GOTO MakeInsert;
ELSE GOTO CreateTable;

CreateTable:
    CREATE TABLE " + tablename + " (ID int IDENTITY(1,1) NOT NULL,Data nvarchar(max) NULL)
MakeInsert:
    INSERT INTO  " + tablename + " (Data) VALUES('" + Message + "')

如果需要创建表,则插入操作也将运行,但反之亦然。

相关问题