将Cursor代码转换为常规SQL代码

时间:2014-05-14 16:05:22

标签: sql sql-server tsql

我有一段游标代码,我试图重写为常规SQL代码但是我收到错误。这是Cursor代码:

FROM            sr_cursor
INTO            @partyID, @serviceRequestID WHILE @@FETCH_STATUS = 0
BEGIN
            SELECT        @customerName = c.TradeName, @legalName = c.LegalName
            FROM            v_RptCompany_v001 c 
            INNER JOIN
                          v_RptAppCompany_v001 ac ON ac.PartyID = c.PartyID AND ac.BeginDate = c.BeginDate
            WHERE        ac.AppID = @gappID AND ac.PartyID = @partyID 
            IF          (@customerName IS NULL OR DATALENGTH(@customerName) = 0) 
BEGIN
SET             @customerName = @legalName 
END

我的代码:

SELECT          C.TradeName as CustomerName, 
            C.LegalName as LegalName, (CASE WHEN CustomerName IS NULL OR DATALENGTH(CustomerName) = 0 THEN CustomerName = LegalName ELSE CustomerName END) AS CustName 
FROM            v_RptCompany_v001 c 
INNER JOIN      v_RptAppCompany_v001 ac 
ON              ac.PartyID = c.PartyID AND ac.BeginDate = c.BeginDate

我怀疑它的案例陈述,因为我收到了错误。请提出可能的答案。感谢您的帮助。先感谢您。

  

请注意:AppID是参数,但我不想拥有任何参数   参数

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT          
   C.TradeName as CustomerName, 
   C.LegalName as LegalName, 
   (CASE WHEN CustomerName IS NULL OR DATALENGTH(CustomerName) = 0 
           THEN LegalName 
           ELSE CustomerName END) AS CustName 
FROM            
   v_RptCompany_v001 c 
INNER JOIN      
   v_RptAppCompany_v001 ac ON ac.PartyID = c.PartyID AND ac.BeginDate = c.BeginDate