如何更新这样? (SQL)

时间:2013-10-07 03:57:34

标签: sql

我有3个数据库:service1,businessrecord和teamAstaffno

1)我想识别两种类型“play”和“mainbusiness”和“error”中的服务类型

-if businessrecord.type,如“play”as“play”

-if businessrecord.other将service1.servicetype与“mainbusiness”匹配

- 如果它满足两个选项应该显示“错误”

2)我只想要与teamAstaffno.staffno匹配的商业记录,因为我只想要团队A记录。

3)最后,我想要一个具有cloumn order_type的表来显示“play”,“mainbusiness”,“error”和“duplicate”

比什么是sql代码?

我按这样输入

    select businessrecord.type, businessrecord.other, businessrecord.staffno;
from service1;
    join  businessrecord;
        on businessrecord.other = service1.servicetype;
    inner join teamAstaffno;
        on businessrecord.staffno = teamAstaffno.staffno

并将记录复制到表proc1

alter table proc1 add order_type Char(50) 
update order_type with "mainbusiness" where businessrecord.type like service1.servicetype
update order_type with "duplicate" where order_type like "mainbusiness" and type like "play"
update order_type with "play" where other like "play" 
update order_type with "Error" where order_type is null

我做错了什么?

如果使用两个表我应该使用join函数吗?代码是什么?

2 个答案:

答案 0 :(得分:1)

您的UPDATE语法不正确

UPDATE <tablename>
SET <columnname> = <somevalue>
WHERE <predicate>

一些dbms&#39;让你为更新加入

UPDATE alias1
SET alias1.column = 'somevalue'
FROM table1 alias1
JOIN table2 alias2 ON alias1.ID = alias2.ForeignID
WHERE alias2.SomeColumn = 'blah'

答案 1 :(得分:0)

如果您需要在WHERE语句中加入,可以这样做:

UPDATE     t1
SET        Col2 = t2.Col2,
           Col3 = t2.Col3,
           Col4 = t2.Col4,
FROM       Table1 t1
INNER JOIN Table2 t2 ON t1.Col1 = t2.Col1
WHERE      t1.Col1 = 'whatever' 
AND        t2.Col3 = 'somethingelse'

所以在你的情况下,我猜它会是这样的:

UPDATE      service1
SET         OrderType = (CASE 
                WHEN businessrecord.type = service1.servicetype THEN 'mainbusiness'
                WHEN order_type = 'mainbusiness' and type = 'play' THEN 'duplicate'
                WHEN other = 'play' THEN 'play'
                WHEN order_type IS NULL THEN 'Error'
            END)
FROM        service1
INNER JOIN  businessrecord
ON          businessrecord.other = service1.servicetype
INNER JOIN  teamAstaffno
ON          businessrecord.staffno = teamAstaffno.staffno

注意:这可能不是您想要的,但至少它会向您展示如何使用CASE语句执行条件更新。

请参阅此处的MSDN文档:http://technet.microsoft.com/en-us/library/ms181765.aspx