2011-09-29 12 views
0

SQL新手,請接受我的道歉。查詢的創建,當病例情況中斷需要協助修復

If HBL_CLNT_CAT._HS_EB_CODE1 = 'BF' then value = TBM_BILLGRP._HS_EB_DET1 
If HBL_CLNT_CAT._HS_EB_CODE2 = 'BF' then value = TBM_BILLGRP._HS_EB_DET2 

_HS_EB_DET#但是超過100個字符添加一個「*」。

在協助下開發了一個查詢,但是它破壞了條件規則,因爲'then語句/操作會失敗,因爲它比條件語句(select _hs_eb_code1 from hbl_cat where hs_eb_code = 'bf',只返回1條記錄)更大。

select 
    case when len(format) > 100 
     then left(format, 100) + '*' 
     else format 
end as format 
from 
    (select 
     case when exists (select _hs_eb_code1 
         from hbl_cat 
         where hs_eb_code = 'bf' 
         ) 
      then tbm_bllgrp._hs_eb_det1 
     end 
    ) as format 
    from tbm_bllgrp 
+1

向hbl_cat添加UNIQUE約束沒有意義嗎?那麼插入重複項時將失敗,而不是在選擇重複項時。 – VladV

回答

2

格式化代碼會幫助您找到錯誤。試試這個:

select 
    case when len(format) > 100 
     then left(format, 100) + '*' 
     else format 
    end as format 
from 
    (select 
     case when exists (select _hs_eb_code1 
         from hbl_cat 
         where hs_eb_code = 'bf' 
         ) 
      then tbm_bllgrp._hs_eb_det1 
     end as format 
    from tbm_bllgrp 
) as tmp 
+0

但似乎你的查詢沒有使用你在描述中提到的'TBM_BILLGRP._HS_EB_DET2'。它也沒有使用這兩個表格之間的任何關係。 –

+0

如果我得到主要查詢工作,然後我添加'_hs_eb_det2'。 – Nobody

1

上面的查詢在幾個地方被打破了。一個工作聲明看起來是這樣的:

SELECT CASE 
    WHEN len(x.myval) > 100 THEN 
     left(x.myval,100) + '*' 
    ELSE 
     x.myval 
    END AS format 
FROM (
    SELECT CASE 
      WHEN h.HS_EB_CODE1 = 'BF' THEN 
       t._HS_EB_DET1 
      WHEN h._HS_EB_CODE2 = 'BF' THEN 
       t._HS_EB_DET2 
      ELSE 
       'unknown option' 
      END AS myval 
     FROM HBL_CLNT_CAT AS h 
     JOIN TBM_BILLGRP AS t ON ??? -- how are the two tables connected? 
    WHERE ??? -- some condition or do you want all rows in the table? 
     ) AS x 

但是你需要先告訴我們,如何TBM_BILLGRP和HBL_CLNT_CAT可以加入,你如何選擇行。
BTW,大寫在SQL-Server中毫無意義。標識符不區分大小寫,只要它們不用雙引號" "或括號[ ]

+0

PostgreSQL?他有sql-server標記。 –

+0

@ypercube:謝謝!我糾正了這一點。通常,SQL-Server也具有不區分大小寫的標識符。請參閱[這裏](http://msdn.microsoft.com/en-us/library/ms175874.aspx) –