Is there anyway i can convert the below 3 sql queries into a single query ?
insert into table1(Name,Age,Type) Select FirstName,Age,'Type1' FROM Table2 where开发者_开发技巧 Type='SK'
insert into table1(Name,Age,Type) Select FirstName,Age,'Type23' FROM Table2 where Type='JK'
insert into table1(Name,Age,Type) Select FirstName,45,'Type64' FROM Table2 where Type='YP'
insert into table1(Name,Age,Type)
Select FirstName,Age,'Type1' FROM Table2 where Type='SK'
union all
Select FirstName,Age,'Type23' FROM Table2 where Type='JK'
union all
Select FirstName,45,'Type64' FROM Table2 where Type='YP'
insert into table1(Name,Age,Type)
Select FirstName,
CASE WHEN Type = 'YP' THEN 45 ELSE Age END,
CASE WHEN Type = 'SK' THEN 'Type1' etc.
FROM Table2
where Type in ('SK', 'JK', 'YP')
EDIT:
It depends here how many types there are. Maybe another table that stores the types and the correpsonding texts ('Type' etc.) would be better instead of a huge case. And same thing for the age.
Try:
Insert table1(Name,Age,Type)
Select FirstName,
Case Type When 'YP' Then 45 Else Age End,
'Type' + Case Type
When 'SK' Then '1'
When 'JK' Then '23'
When 'YP' Then '64' End
From Table2
Where Type In ('SK', 'JK', 'YP')
Try..
insert into table1(Name,Age,Type)
(Select FirstName,
(case when type='YP' then
45
else
age
end) age,
(case when type='SK' then
'Type1'
when type='JK' then
'Type23'
when type='YP' then
'Type64'
end) type
FROM Table2 where Type in ('SK','JK','YP'))
精彩评论