带有WHERE子句的SQL Server COALESCE函数

时间:2015-08-14 05:35:13

标签: sql-server coalesce

我想在Varchar参数中连接我的SQL Server表的列值。为此我使用COALESCE函数。但是当我将Select语句与Where子句一起使用时,我认为它没有采用where子句条件。

SELECT 
    @UserIds = COALESCE(@UserIds,'') + CONVERT(VARCHAR(MAX), UserID) +','      
FROM vw_Users               
WHERE GroupID = @GroupID                                        
  AND ISNULL(Active_yn, 'Y') = 'Y'            
  AND ISNULL(Delete_YN, 'N') = 'N' 

那么有人可以帮我解决这个问题吗?

3 个答案:

答案 0 :(得分:0)

如果corecctly了解您的问题,您可以使用CASE之类的内容:

SELECT 
    CASE WHEN ISNULL(Active_yn, 'Y') = 'Y' 
              AND ISNULL(Delete_YN, 'N') = 'N' 
              AND GroupID = @GroupID THEN @UserIds = COALESCE(@UserIds,'') + CONVERT(VARCHAR(MAX), UserID) +','  
         ELSE Condition 
    END    
FROM vw_Users               

在这种情况下,只有当所有条件都满足时它才会连接,否则你可以将条件传递给ELSE

答案 1 :(得分:0)

您的查询看起来很好,条件正确,只需对COALESCE函数进行少量更改即可连接","只在需要时。这是一个包含数据的示例:

DECLARE @UserIds VARCHAR(100);
DECLARE @GroupID INT = 1;

WITH vw_Users (UserID, GroupID, Active_YN, Delete_YN) AS (
    SELECT 1, 1, 'Y', 'N' UNION ALL -- valid value
    SELECT 2, 1, 'Y', 'N' UNION ALL -- valid value

    SELECT 3, 1, 'N', 'N' UNION ALL -- invalid value because Active_YN <> 'Y'
    SELECT 4, 1, 'Y', 'Y' UNION ALL -- invalid value because Deleted_YN <> 'N'
    SELECT 5, 2, 'Y', 'N'           -- invalid value because GroupID <> 1
)
SELECT 
    @UserIds = COALESCE(@UserIds + ',','') + CONVERT(VARCHAR(MAX), UserID)
FROM vw_Users               
WHERE GroupID = @GroupID                                        
  AND ISNULL(Active_yn, 'Y') = 'Y'            
  AND ISNULL(Delete_YN, 'N') = 'N' 

SELECT @UserIds --> 1,2

答案 2 :(得分:0)

你应该尝试以下,

Declare @cols nvarchar(max) = ''
SELECT  @cols = 
STUFF(( SELECT DISTINCT TOP 100 PERCENT
        ',' + CONVERT(VARCHAR(10), t2.UserID)
        FROM  vw_Users AS t2
        WHERE GroupID = @GroupID                                        
        AND ISNULL(Active_yn, 'Y') = 'Y'            
        AND ISNULL(Delete_YN, 'N') = 'N' 
        FOR XML PATH('')
), 1, 1, '')

select @cols

这是Sql fiddle