在where语句

时间:2016-06-20 23:49:14

标签: c# sql-server linq

我有这个Linq查询:

IQueryable<SPR> query = db.SPRs;

if (!string.IsNullOrEmpty(search.accountNumber))
{
    query = query.Where(b => b.CustomerAccountNumber.Contains(search.accountNumber));
}

if (!string.IsNullOrEmpty(search.accountName))
{
    query = query.Where(b => b.CustomerNumber.Contains(search.accountName));
}

if (!string.IsNullOrEmpty(search.submittedBy))
{
    query = query.Where(b => b.SubmittedBy.Contains(search.submittedBy));
}

if (!string.IsNullOrEmpty(search.smName))
{                   
    query = query.Where(b => b.SMUserName == search.smName);
}                    

var result = query.ToList();

如果条件为真,我只是附加where子句。问题是它不仅仅是在我想要的生成的SQL where子句中添加And。

如果我有SubmittedBySMUserName填充了数据,那么这是生成的SQL。

SELECT 
    [Extent1].[Id] AS [Id], 
    [Extent1].[CustomerNumber] AS [CustomerNumber], 
    [Extent1].[CustomerAccountNumber] AS [CustomerAccountNumber], 
    [Extent1].[SMUserName] AS [SMUserName], 
    [Extent1].[SubmittedBy] AS [SubmittedBy], 
    [Extent1].[Notes] AS [Notes]
FROM 
    [dbo].[SPRs] AS [Extent1]
WHERE 
    ([Extent1].[SubmittedBy] LIKE @p__linq__0 ESCAPE N'~') 
    AND (([Extent1].[SMUserName] = @p__linq__1) OR (([Extent1].[SMUserName] IS NULL) 
    AND (@p__linq__1 IS NULL)))

不确定最后一行OR (([Extent1].[SMUserName] IS NULL) AND (@p__linq__1 IS NULL)))是如何添加的,这会弄乱查询。

当if条件满足时,有人可以告诉我如何在最终查询中使用AND吗?

1 个答案:

答案 0 :(得分:2)

由于您正在使用sql server,因此更高性能和更流畅的方法是处理存储过程中的可选参数,并使用带有sp_executesql的Dynamic sql从Parameterised Execution Plans中受益。

CREATE PROCEDURE getSPR
 @SubmittedBy           Varchar(100) = NULL     --<--- Use appropriate datatypes
,@CustomerAccountNumber Varchar(100) = NULL
,@CustomerNumber        Varchar(100) = NULL
,@SMUserName            Varchar(100) = NULL
AS
BEGIN
  SET NOCOUNT ON;

Declare @Sql Nvarchar(max);

SET @Sql = N'SELECT [Id] 
              ,[CustomerNumber] 
              ,[CustomerAccountNumber] 
              ,[SMUserName] 
              ,[SubmittedBy] 
              ,[Notes] 
        FROM [dbo].[SPRs] 
        WHERE 1 = 1 '
        + CASE WHEN @SubmittedBy IS NOT NULL THEN 
          N' AND [SubmittedBy] LIKE ''%'' + @SubmittedBy + ''%''' ELSE N' ' END
        + CASE WHEN @CustomerAccountNumber IS NOT NULL THEN  
          N' AND [CustomerAccountNumber] LIKE ''%'' + @CustomerAccountNumber + ''%''' ELSE N' ' END
        + CASE WHEN @CustomerNumber IS NOT NULL THEN  
          N' AND [CustomerNumber] LIKE ''%'' + @CustomerNumber + ''%''' ELSE N' ' END
        + CASE WHEN @SMUserName IS NOT NULL THEN  
          N' AND [SMUserName] = @SMUserName ' ELSE N' ' END

Exec sp_executesql @sql 
                  ,N' @SubmittedBy Varchar(100),@CustomerAccountNumber Varchar(100)
                     ,@CustomerNumber Varchar(100), @SMUserName Varchar(100)'
                  ,@SubmittedBy
                  ,@CustomerAccountNumber
                  ,@CustomerNumber
                  ,@SMUserName

END