2013-04-10 52 views
3

我爲Organization表創建插入查詢。在SQL Server中創建帶有空值的插入查詢

select 'Insert into Organizations(Name, IndustryId, ContactPerson, Email, Website, LocationId, ContactNumber, Mobilenumber) values(''' + 
     IsNull(Nameofthecompany, 'NULL') + ''',' + 
     Isnull(IndustryType, 'NULL') + ',''' + 
     Isnull(Nameofthepersonresponsibleforrecruitment, 'NULL') + ''', ''' + 
     Isnull(EmailId, 'NULL') + ''', ''' + 
     Isnull(websiteaddress, 'NULL') + ''',' + 
     Isnull(Location, 'NULL') + ',' + 
     Isnull(PhoneNumber, 'NULL') + ',' + 
     Isnull(MobileNumber, 'NULL') + ')' 
from Organization 

這裏我有結果集

Insert into Organizations(Name, IndustryId, ContactPerson, Email, Website, LocationId, ContactNumber, Mobilenumber) 
values('username', industry, 'Name', 'NULL', 'NULL', place, NULL, 999999999) 

我不想引號中的NULL值。如果我刪除引號意味着我得到錯誤。請幫助我找出問題所在。

+2

什麼是錯誤?也許這些列不是空的! – 2013-04-10 04:57:41

+0

那麼,你想要什麼**而不是「NULL」?只需將它們替換爲你想添加的內容..... – 2013-04-10 05:00:30

+0

向我顯示你的列定義。如果您的列'allow Null' – 2013-04-10 05:01:39

回答

2

如果值爲NULL,則將其添加到字符串將產生NULL。 這允許我們在ISNULL檢查中添加引號,並在檢查的真實值中產生NULL,根據需要爲空值或非空值生成正確的語法。

select 'Insert into Organizations(Name, IndustryId, ContactPerson, Email, Website, LocationId, ContactNumber, Mobilenumber) values(' + 
     IsNull(''''+Nameofthecompany+'''', 'NULL') + ', ' + 
     Isnull(''''+IndustryType+'''', 'NULL') + ', ' + 
     Isnull(''''+Nameofthepersonresponsibleforrecruitment+'''', 'NULL') + ', ' + 
     Isnull(''''+EmailId+'''', 'NULL') + ', ' + 
     Isnull(''''+websiteaddress+'''', 'NULL') + ', ' + 
     Isnull(''''+Location+'''', 'NULL') + ', ' + 
     Isnull(PhoneNumber, 'NULL') + ', ' + 
     Isnull(MobileNumber, 'NULL') + ')' 
from Organization 
2

如果你想使用NULL(如文字 - 不是一個字符串)爲您的NULL值,則該INSERT聲明的創作得到了很多更復雜;如果值爲NULL,那麼您需要添加文字NULL而不是前導和尾隨'

對於要做到這一點,你需要使用一個CASE聲明每一列 - 這樣的事情:

select 'INSERT INTO Organizations(.....) ' + 
     'VALUES(' + 
     CASE 
      WHEN NameOfTheCompany IS NOT NULL 
       THEN '''' + NameOfTheCompany + ''', ' 
       ELSE 'NULL, ' 
     END + 
     CASE 
      WHEN IndustryType IS NOT NULL 
       THEN '''' + IndustryType + ''', ' 
       ELSE 'NULL, ' 
     END + 
     ..... and so on ...... 
     + ')' 

...等,爲每列你需要這個CASE聲明...

+0

奇怪這似乎是關於如何故意插入null我可以在網上找到的唯一一點信息!假設它只是假定的知識 – 2013-12-02 17:28:55