动态过程,删除最后一个字符串字符

时间:2015-06-25 09:14:30

标签: sql sql-server sql-server-2008 tsql

我有一个动态生成UNION ALL的参数 取决于输入。

    SELECT @CMD +=N'

 SET NOCOUNT ON;     
 SELECT
     COUNT(CASE WHEN RFRD.QueuTypeID=4
           THEN RFRD.QueuTypeID
           END) RequiredaQueue

             ,COUNT(DISTINCT RFRD.LeadDocumentID) AS Repeat,CONCAT('''+RF+''' ,'' '') AS RiskFactorID
        FROM FCT.RiskMng_fact_RiskFactorResultDetails AS RFRD


    UNION ALL

 SELECT
     COUNT(CASE WHEN RFRD.QueuTypeID=4
           THEN RFRD.QueuTypeID
           END) RequiredaQueue

         ,COUNT(DISTINCT RFRD.LeadDocumentID)AS Repeat,CONCAT('''+RF+''' ,''*'')  AS RiskFactorID
        FROM FCT.RiskMng_fact_RiskFactorResultDetails AS RFRD'
        --------------
            FROM #cte RF    
EXEC sys.sp_executesql @CMD     

最后我想将它们全部连接成一个长UNION,所以我最后添加了一个UNION ALL:

          SELECT @CMD +=N'

 SET NOCOUNT ON;     
 SELECT
     COUNT(CASE WHEN RFRD.QueuTypeID=4
           THEN RFRD.QueuTypeID
           END) RequiredaQueue

             ,COUNT(DISTINCT RFRD.LeadDocumentID) AS Repeat,CONCAT('''+RF+''' ,'' '') AS RiskFactorID
        FROM FCT.RiskMng_fact_RiskFactorResultDetails AS RFRD


    UNION ALL

 SELECT
     COUNT(CASE WHEN RFRD.QueuTypeID=4
           THEN RFRD.QueuTypeID
           END) RequiredaQueue

         ,COUNT(DISTINCT RFRD.LeadDocumentID)AS Repeat,CONCAT('''+RF+''' ,''*'')  AS RiskFactorID
        FROM FCT.RiskMng_fact_RiskFactorResultDetails AS RFRD'
        --------------
        +' UNION ALL '  <-----------------------


FROM #cte RF    
EXEC sys.sp_executesql @CMD     

运行后,最后一个UNION ALL是Needless,
我得到错误:

            ON  OU.ID = RFRD.Entity_OrganizationUnitID
            INNER JOIN #Entity_OrganizationUnitTypeIDs OUT
                ON  OUT.ID = RFRD.Entity_OrganizationUnitTypeID         

        WHERE   RFRD.EntityTypeID = 1055
        and RFRD.riskfactorid IN(6249,6102)
             AND RFRD1.ID IS NULL  
              UNION ALL 

Msg 156,Level 15,State 1,Line 118

任何人都可以建议我如何才能删除最后一个UNION ALL? 也许我不应该在最后添加一个UNION AL? 感谢

3 个答案:

答案 0 :(得分:0)

最后你需要通过

删除它
set @CMD = substring(@CMD,1,len(@CMD)-9)
EXEC sys.sp_executesql @CMD  

答案 1 :(得分:0)

UNION ALL命令采用两个参数,即之前的表和UNION ALL命令之后的表。

所以它应该总是有形式

SELECT col1,col2 FROM A
UNION ALL
SELECT col3 as col1,col4 as col2 FROM B

答案 2 :(得分:0)

当您连接SELECT语句时,为什么不检查现有字符串是否为空,然后仅在需要时添加UNION ALL,例如:

SELECT @CMD = @CMD + 
       CASE WHEN @CMD = '' THEN '' ELSE ' UNION ALL ' END + 
       'SELECT ... '

然后你不会再遇到任何问题。