2013-04-10 50 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