从SQL Server中的视图返回的结果取决于" ="或" IN"用过的

时间:2017-01-11 14:27:40

标签: sql-server view

我在SQL Server 2008中创建了一个视图,根据我是否使用" ="或" IN"查询时。

例如,我可以运行:

SELECT * FROM UsersToMigrate WHERE u_s_p_no = 123

...并且它不返回任何记录。

但是,如果我跑:

SELECT * FROM UsersToMigrate WHERE u_s_p_no in (123, 456)

...然后按预期返回两个值的记录。

视图基于4个子查询,它们是UNION ALL。第一个子查询使用分析函数row_number():

Select  
    Replace(SPMF.FirstName,',',' ') [FirstName],
    Replace(SPMF.Surname,',',' ') [SurName],
    SPMF.sp_email [Email],
     UA.username,
    UA.DomainLogon [DomainLogon],
    Case    When SPMF.TeamLevel = 3 And CL.cw_type in (2,6,10,14) Then 'Adult Social Care - Practitioner'
            When SPMF.TeamLevel = 2 And CL.cw_type in (2,6,10,14) Then 'Adult Social Care - Team Manager'
            When SPMF.TeamLevel = 3 And CL.cw_type in (1,4,5,9,12,13) Then 'Children Social Care - Practitioner'
            When SPMF.TeamLevel = 2 And CL.cw_type in (1,4,5,9,12,13) Then 'Children Social Care - Team Manager'
            When CL.cw_type in (2,6,10,14) Then 'Adult Social Care - Practitioner'
            When CL.cw_type in (1,4,5,9,12,13) Then 'Children Social Care - Practitioner'
            Else 'Adult Social Care - Practitioner'
    End [Role],
    password [EncryptedPassword],
    CL.OwningBusinessUnit [BusinessUnit],
    Case When ISNULL(UA.Status,1) = 1 Then 0 Else 1 End [Disabled],
    null [Owner],
    UA.date_setup [CreatedOn],
    u_s_p_no,
    defaultRole,
    CL.cw_type [cw_type]
From    (select * from (
            select *, row_number() over (partition by u_s_p_no order by status) as rownum1
            from useraccess) as x
         where rownum1 = 1) UA
Inner   Join (select * from (
                 select *, row_number() over (partition by s_p_no order by s_p_no) as rownum2
                 from ServiceProviderMasterFile) as y
              where rownum2 = 1) SPMF
Left    Join sp_class CL WITH (NOLOCK) On CL.Category = spmf.sp_cat and CL.class = spmf.sp_class
Where   IsNull(UA.IncludeInExport,1) = 1

我只是想知道这个分析功能是否可能与问题有关?

有没有人经历过这样的事情?有什么想法可能会发生吗?

由于

1 个答案:

答案 0 :(得分:0)

如果你这样做

SELECT * FROM UsersToMigrate WHERE u_s_p_no in (123, 456);
SELECT * FROM UsersToMigrate WHERE u_s_p_no = 123;
SELECT * FROM UsersToMigrate WHERE u_s_p_no  = 456;
SELECT * FROM UsersToMigrate WHERE u_s_p_no  = 123 OR u_s_p_no  = 456;

(1)在逻辑上与(4)相同 - (2)和(3)返回的记录应与(4)匹配 - 否则数据在某处被更改?

您最初描述的问题确实是问题吗?它是否以这种简单的形式存在?

如果在更简单的SQL中出现问题,那么显示的较大的SQL是什么?

为什么较大的SQL似乎缺少一些东西?它是'真正的'SQL吗?