SQL Server 2014如果存在多个开始和结束

时间:2017-10-03 12:09:58

标签: sql sql-server

我有这行代码:

if exists(select a.id, a.user_id 
          from AEmployeeLogs a
          inner join AUsers b on b.id = a.user_id
          where b.username = @username 
            and b.password = @password
            and convert(date, a.date_in) = convert(date, dateadd(HOUR, 15, getdate())))
    select 'Exist' as result;
else
begin
    select 
        a.id, username, firstname, lastname, user_image, UserType, title,
        'user_type_title', is_cashier, 
        case
           when @num is null then 1
           else @num + 1
        end 'number'
    from 
        dbo.AUsers a
    inner join 
        ALookUp b on b.id = a.UserType
    left join
        AEmployeeLogs c on c.user_id = a.id
    where 
        a.username = @username and a.password = @password

end

    declare @id int;
    select @id = a.id
    from dbo.AUsers a
    INNER JOIN ALookUp b
    on b.id = a.UserType            
    where username = @username and password = @password

begin

        INSERT INTO AEmployeeLogs (date_in,[user_id],note,isactive)
        select dateadd(HOUR, 15, getdate()), @id, '',0
        where @id is not null

end     

If Exists函数正常工作,但是当我查看表AEmployeeLogs时,它仍然会插入,即使存在,当我有多个开始和时,编写我的else语句的正确方法是什么我的查询中的结束函数

注意:第一个开始和结束工作它没有选择,但第二个工作需要帮助

1 个答案:

答案 0 :(得分:3)

正如评论中已经说明的那样,else的范围已经在第一个end之后结束。

如下所示,它应该按预期工作:

IF EXISTS (
        SELECT a.id,
            a.user_id
        FROM AEmployeeLogs a
        INNER JOIN AUsers b ON b.id = a.user_id
        WHERE b.username = @username
            AND b.password = @password
            AND CONVERT(DATE, a.date_in) = CONVERT(DATE, dateadd(HOUR, 15, getdate()))
        )
    SELECT 'Exist' AS result;
ELSE
    BEGIN
        SELECT a.id, username, firstname, lastname, user_image, UserType, title, 'user_type_title', is_cashier, 
            CASE 
                WHEN @num IS NULL
                    THEN 1
                ELSE @num + 1
                END 'number'
        FROM dbo.AUsers a
        INNER JOIN ALookUp b ON b.id = a.UserType
        LEFT JOIN AEmployeeLogs c ON c.user_id = a.id
        WHERE a.username = @username
            AND a.password = @password

        DECLARE @id INT;

        SELECT @id = a.id
        FROM dbo.AUsers a
        INNER JOIN ALookUp b ON b.id = a.UserType
        WHERE username = @username
            AND password = @password

        INSERT INTO AEmployeeLogs (
            date_in,
            [user_id],
            note,
            isactive
            )
        SELECT dateadd(HOUR, 15, getdate()),
            @id,
            '',
            0
        WHERE @id IS NOT NULL
    END