根据条件,sql server将值插入表中

时间:2013-08-08 05:26:14

标签: sql-server tsql stored-procedures sql-insert

我尝试根据条件在存储过程中将值插入到表中:

alter procedure service_report_st2
as
insert into Service_report_step1(appointment_or_house) 
select
case
when Service_report_step1.card_uid in(select card_uid from visits where vidpos_kod = 'A')
then '1'

when Service_report_step1.card_uid in(select card_uid from visits  where vidpos_kod = 'B')
then '2'

else '3'
end

错误在Service_report_step1.card_uid找不到,但这是Service_report_step1表中的第一列。 appointment_or_house是第二列,如果visits表格在card_uid中包含Service_report_step1,则应包含“1”,“2”或“3”。

我很感激任何帮助!

简短的例子:

Visits表有2列:Card_uid和vidpos_kod

card_uid         vidpos_kod
 111-111              A
 222-222              B
 333-333              A
 444-444              C

现在Service_report_step1表有card_uid(包含所有可能卡的列)和appointment_or_house列

card_uid      appointment_or_house
 111-111              1
 222-222              2
 333-333              1
 444-444              1

所以,如果card_uids中的Service_report_step1Visits中的appointment_or_house相同,我会根据vidpos_kod中的Visits确定A, C列( B为'1',Service_report_step1为'2')

我需要正确插入{{1}}所有数据,例如。

2 个答案:

答案 0 :(得分:2)

您正在使用select语句,但没有FROM clause

您需要指定

INSERT INTO ...
SELECT *
FROM ...

或类似的东西。

另一种选择是使用Table Value Constructor (Transact-SQL)

答案 1 :(得分:2)

insert into Service_report_step1(appointment_or_house) 
select
case vidpos_kod
when 'A' then '1'
when 'B' then '2'
when 'C' then '3'
end
from visits 
where vidpos_kod like '[ABC]'
相关问题