2016-07-30 91 views
0

我試圖插入數據通過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控制檯應用程序要做到這一點它拋出異常!

回答

1

,如果它不存在,你的代碼檢查,它創造並插入數據的話,卻跳過了其他部分 表所在,那麼你只插入數據

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

我已經嘗試了上面的代碼,但其引發的語法錯誤「無效語法附近ELSE」 @Zeina –

+0

感謝您的回答哥們,但在這裏拋出異常「已經有一個對象名稱「tablename」.. @ Zeina –

+0

一定有什麼問題......因爲我們沒有創建表,除非它不存在...在我的電腦上它工作正常! PLZ recheck我們的代碼 – Zeina