搜索数据库有多个选项

时间:2011-07-16 06:00:06

标签: c# sql sql-server search stored-procedures

我使用SQL Server 2008 Express和高级服务。我有一个观点:

IF EXISTS (select * from sys.views where object_id = object_id(N'[dbo].[vw_PersonDetails]'))
    DROP VIEW vw_PersonDetails
GO

CREATE VIEW vw_PersonDetails
AS
    SELECT
        p.PersonID, p.Title, 
        p.FirstName, p.LastName,
        a.AddressLine1, a.AddressLine2, a.AddressLine3, a.AddressLine4,
        a.Country, a.PostalCode, 
        a.PhoneNumber, a.Email, p.EntryDate
    FROM  
        [dbo].[Persons] p
    INNER JOIN 
        [dbo].[Address] a ON p.PersonID = a.PersonID
GO

现在我必须使用每个列作为选项搜索此视图。

例如:

IF (@firstName != NULL OR @firstName != '') AND 
   (@lastName != NULL OR @lastName != '') AND 
   (@addressLine1 != NULL OR @addressLine1 != '') AND 
   (@postalCode != NULL OR @postalCode != '') AND 
   (@country != NULL OR @country != '') AND
   (@phoneNumber != NULL OR @phoneNumber != '') AND 
   (@email != NULL OR @email != '') AND 
   (@entryDate != NULL)
BEGIN
    SELECT * 
    FROM dbo.vw_PersonDetails 
    WHERE 
        (FirstName LIKE [dbo].[GetSearchString](@firstName) OR
        LastName LIKE [dbo].[GetSearchString](@lastName) OR
        AddressLine1 LIKE [dbo].[GetSearchString](@addressLine1) OR
        Country LIKE [dbo].[GetSearchString](@country) OR
        PostalCode LIKE [dbo].[GetSearchString](@postalCode) OR
        PhoneNumber LIKE [dbo].[GetSearchString](@phoneNumber) OR
        Email LIKE [dbo].[GetSearchString](@email) OR
        EntryDate = @entryDate
       )
END

除了在存储过程中编写永不停止的IF-ELSE-IF跟踪或动态构建查询之外,现在还有其他选择。请帮忙。

另一个问题是什么会更好:编写这样的存储过程或从代码中进行动态查询。

提前致谢。

2 个答案:

答案 0 :(得分:1)

您需要为查询填充所有SearchString才能运行(因为IF语句中的AND条件)。

无论参数是否通过,您都可以创建一个动态查询来运行:

DECLARE @sqlCommand VARCHAR(MAX)
SELECT @sqlCommand = 'SELECT * FROM dbo.vw_PersonDetails WHERE 1=1'

IF  (@firstName != NULL OR @firstName != '') SELECT @sqlCommand = @sqlCommand + ' AND FirstName LIKE [dbo].[GetSearchString](@firstName)'
IF  (@lastName != NULL OR @lastName != '') SELECT @sqlCommand = @sqlCommand + ' AND LastName LIKE [dbo].[GetSearchString](@lastName)'
IF  (@addressLine1 != NULL OR @addressLine1 != '') SELECT @sqlCommand = @sqlCommand + ' AND AddressLine1 LIKE [dbo].[GetSearchString](@addressLine1)'

.....

EXEC (@sqlCommand)

答案 1 :(得分:1)

您可以在一个简单的查询中执行此操作:

SELECT * from dbo.vw_PersonDetails WHERE (
    (@firstName IS NULL OR @firstName = '' OR FirstName like @firstName) AND
    ... (same thing for other parameters)

这将起作用,因为SQL Server足够智能,可以按预期方式短路评估。但是,规范实际上并未保证这一点。

如果您想要安全起见,可以通过以下方式强制执行评估顺序:

SELECT * from dbo.vw_personDetails WHERE (
    (CASE 
        WHEN @firstname IS NULL THEN 1
        WHEN @firstname='' THEN 1
        WHEN FirstName like @firstName THEN 1
        ELSE 0
     END=1) AND
    .... (same thing for other parameters)