T-SQL IF CLAUSE SYNTAX

时间:2017-03-24 17:36:03

标签: sql-server tsql

我正在尝试根据各种参数建立一个用于安排邮件列表的sp,并且到目前为止工作正常:

DECLARE
@out_desc VARCHAR(1000),@out_mesg VARCHAR(10),@tableHTML  NVARCHAR(MAX),@frequency INT,@userName    NVARCHAR(50),@userEmail NVARCHAR(50),
@category NVARCHAR(50),@range INT,@geoid int,@IsDeleted BIT,@searchCity NVARCHAR(50);

DECLARE C1 CURSOR READ_ONLY
FOR
SELECT [userEmail], AspNetUsers.[UserName], [frequency], [category], [range], [geoid], [searchCity], [IsDeleted] FROM WishLists
JOIN AspNetUsers ON WishLists.userEmail = AspNetUsers.Email

OPEN C1
FETCH NEXT FROM C1 INTO
@userEmail, @userName,@frequency, @category,@range, @geoid, @searchCity, @IsDeleted
WHILE @@FETCH_STATUS = 0
BEGIN
      IF @frequency = 1
      BEGIN
            SET @tableHTML =  
    N'<H1>Hello' +  @userName +
    N'<table border="1"><tr><th>Department</th>th>Name</th><th>Description</th><th>Place</th></tr>' +  

        CAST (( SELECT td = c.Name, '',   td = p.Name, '',   td = p.Description, '', td = @searchCity
                  FROM Products as p JOIN Categories AS c ON c.ID = p.CategoryID  JOIN AspNetUsers as u ON u.ID = p.UserID WHERE (p.IsApproved = 'true' AND p.IsDeleted = 'false'  AND u.Email = @userEmail) AND DateExpire > convert(date, getdate())
                  FOR XML PATH('tr'), TYPE   
        ) AS NVARCHAR(MAX) ) 
    +  
    N'</table>' ; 

    EXEC sp_send_mail
    ...

这可以按预期工作。 现在我已经测试了电子邮件功能,我需要用另一个“IF”子句进一步详细说明SELECT,其中选择了特定的地理位置。

我正在尝试插入这个新的IF子句,以这种方式添加另一个SELECT:

    ...
N'<th>Place</th></tr>' +  

        CAST (
IF @geoid = 0 (
    (SELECT td = c.Name, '',  
                        td = p.Name, '',  td = p.Description, '', td = @searchCity
                  FROM Products as p 
                  ...)
                  FOR XML PATH('tr'), TYPE   
        ) AS NVARCHAR(MAX) 
)
ELSE
    (...geoid > 0 => another select here...)
    ) 
    +  
    N'</table>' ; 

但只是插入 IF @geoid = 0 () 阻止它看起来像语法有问题。 我做错了什么?

1 个答案:

答案 0 :(得分:1)

使用case语句而不是IF,如下所示

N'<th>Place</th></tr>' +  

        CAST (
CASE WHEN @geoid = 0 THEN (
    (SELECT td = c.Name, '',  
                        td = p.Name, '',  td = p.Description, '', td = @searchCity
                  FROM Products as p 
                  ...)
                  FOR XML PATH('tr'), TYPE   
        ) AS NVARCHAR(MAX) 
)
ELSE
    (...geoid > 0 => another select here...)
    ) 
    +  
    N'</table>' ; 

因为If语句不能在其他操作中使用,如SELECT或SET

像这样的东西

DECLARE @V_String VARCHAR(MAX)
SELECT 
    @V_String = CASE WHEN SalesOrderID%2 = 1
                    THEN (SELECT DueDate FROM SalesLT.SalesOrderHeader FOR XML PATH(''))
                ELSE (SELECT ShipDate FROM SalesLT.SalesOrderHeader FOR XML PATH('')
                ) 
                END
    FROM SalesLT.SalesOrderHeader S

SELECT
    @V_String