2013-10-17 77 views
0

我有8位列,A1,A2,a3,a4,b1,b2,b3,b4。所有8個都是完全獨立的,並且基於這些應該填充另一個字段。具有案例/ IF的SQL更新

我想更新與文本A,B或AB,這取決於任何8列被設置爲1。

下面是兩個例子這個其他字段; - 所有8個字段被設置爲1,然後用AB填充,
- 如果A3和B1被設置爲1,然後用AB填充,
- 如果A1和A3被設置爲1,然後用甲填充,
- 如果B4和B2被設置爲1,則與B填充

所以通過B4 A1的任意組合的字段應該設置

下面是什麼,我都試過,但它是不完整的,但會給一個想法;

UPDATE

從adrianm

UPDATE m 
SET ref = ASet + BSet 
FROM contactMaster m 
inner join contact c on 
m.contactid = c.contactid 
CROSS APPLY (
    SELECT CASE WHEN (c.A1 | c.A2 | c.A3 | c.A4) = 1 THEN 'C' ELSE '' END AS ASet 
      ,CASE WHEN (c.B1 | c.B2 | c.B3 | c.B4) = 1 THEN 'D' ELSE '' END AS BSet 
) AS CA1 
where ref is null 
正確答案
+1

您的需求是不是真的清楚。您沒有提及是否只有兩列只能同時設置爲'1',或者允許多個列。 – hallie

+0

允許多個。所有8個都是完全獨立的,其基礎是其他領域應該被填充。 – windowskm

+0

請花你的時間來編輯你的問題,並添加更多的細節。告訴我們您的確切要求是什麼,您嘗試過的內容(包括代碼)以及您爲什麼陷入這些解決方案,幫助我們重現情況等等。 – Jeroen

回答

2
UPDATE ContactMaster 
    SET ref = ASet + BSet 
FROM ContactMaster 
    INNER JOIN Contact 
      ON ContactMaster.ContactId = Contact.ContactId 
    CROSS APPLY (
     SELECT CASE WHEN (Contact.A1 | Contact.A2 | Contact.A3 | Contact.A4) = 1 THEN 'A' ELSE '' END AS ASet 
       ,CASE WHEN (Contact.B1 | Contact.B2 | Contact.B3 | Contact.B4) = 1 THEN 'B' ELSE '' END AS BSet 
    ) AS CA1 
WHERE ContactMaster.ref IS NULL 
0
IF (Select Count(*) from table where A1=1 AND A2 =1 AND a3 =1 AND a4 =1 AND b1 =1 AND b2 =1 AND b3 =1 AND b4=1)>0 
    BEGIN 

    UPDATE MyTable 
    SET ColumnValue ='AB' 
    where A1=1 AND A2 =1 AND a3 =1 AND a4 =1 AND b1 =1 AND b2 =1 AND b3 =1 AND b4=1 
    END 

    ELSE IF (Select Count(*) from table where A1 =1 and A3 =1)>0 

    BEGIN 
    Update MyTable set columnValue ='A' 
    where A1 =1 and A3 =1 
    END