我为比较男性和女性创建了select语句并替换了一些值。我有两张桌子。
表1:
表2:
我想创建表2到表1的select语句。我的查询如下,
select 'insert into table1(Male,female)values('+
Isnull(cast(case Gender when 'M' or 'B' Then '''True''' else '''false''' end as varchar),'NULL')+','+
Isnull(cast(case Gender when 'F' or'B' Then '''True''' else '''false''' End as varchar),'NUll')+')'
from Table2
但我得到错误或运营商不在这里使用。如何使用运算符选择两个值。有人建议我......
答案 0 :(得分:2)
您可以尝试这样:
select 'insert into table1(Male,female)values('+
Isnull(cast(case when Gender = 'M' or Gender = 'B' Then '''True''' else '''false''' end as varchar),'NULL')+','+
Isnull(cast(case when Gender = 'F' OR Gender = 'B' Then '''True''' else '''false''' End as varchar),'NUll')+')'
from Table2
或者像这样:
select 'insert into table1(Male,female)values('+
Isnull(cast(case Gender when 'M' Then '''True''' when 'B' Then '''True''' else '''false''' end as varchar),'NULL')+','+
Isnull(cast(case Gender when 'F' Then '''True''' when 'B' Then '''True''' else '''false''' End as varchar),'NUll')+')'
from Table2
答案 1 :(得分:2)
要使用动态SQL,您需要声明一个变量。它还可以帮助您进行代码测试
DECLARE @dml nvarchar(max) = N''
select @dml += 'insert into table1(Male,female)values('+
Isnull(cast(case when Gender IN('M', 'B')
Then '''True''' else '''false'''
end as varchar),'NULL')+','+
Isnull(cast(case when Gender IN('F', 'B')
Then '''True''' else '''false'''
end as varchar),'NUll')+')' + CHAR(13) + CHAR(10)
from Table2
PRINT @dml
答案 2 :(得分:1)
select 'insert into table1(Male,female)values('+
Isnull(cast(case Gender when 'M' or Gender when 'B' Then '''True''' else '''false''' end as varchar),'NULL')+','+
Isnull(cast(case Gender when 'F' or Gender when 'B' Then '''True''' else '''false''' End as varchar),'NUll')+')'
from Table2
尝试此查询。
希望它有用。