我希望将几个 SQL Server 查询压缩到一个查询中,这样一个参数就可以用于不同的数据类型。这些类型是日期、数字或字符串。该参数称为:@SearchValue。
在强类型数据集中,我们有下面列出的 3 个查询。
这适用于带有 VB.Net 代码隐藏文件的 ASP.Net,但我认为这个问题也可能适用于非 ASP.Net。
如果用户在搜索文本框中输入日期,我称之为:
询问:
SELECT ID, PaymentAmount, PaymentDate, WhatWasPaymentFor
FROM Payments
WHERE (ParentID = @ParentID) AND
(PaymentDate = @SearchValue)
从 VB.Net 代码隐藏调用日期搜索查询:
tblObject = theTableAdapter.GetDataByPaymentDate(dcmParentsId, TextBoxSearch.Text)
If tblObject.Count() > 0 Then
GridViewSummary.DataSource = tblObject
GridViewSummary.DataBind()
End If
其他的仅用于数字,最后一个用于其他所有内容。
这个仅用于数字:
SELECT PaymentDate, PaymentAmount, WhatWasPaymentFor, ID
FROM Payments
WHERE (ParentID = @ParentID) AND
(PaymentAmount = @SearchValue)
当其他 2 个查询未找到任何数据时,将调用此一个:
SELECT PaymentDate, PaymentAmount, WhatWasPaymentFor, ID
FROM Payments
WHERE (ParentID = @ParentID) AND
((WhatWasPaymentFor LIKE '%' + @SearchValue + '%') OR
(@SearchValue = 'ALL'))
所有这些编码都按原样工作,我这样做是因为如果我尝试使用非日期值调用 .GetDataByPaymentDate 会出现错误。
有没有办法使用单个查询来处理按日期、数字和字符串进行的搜索?
* 更新 *
感谢所有示例查询。我正在尝试 SQL Server Management Studio 中的所有示例查询,看看会出现什么结果。
我这个基于 Gordon 的查询,但它不返回任何数据:
DECLARE @SearchValue VARCHAR = '01/01/2012'
DECLARE @SearchType VARCHAR = 'Dates'
DECLARE @ParentID INT = 3
SELECT ID, PaymentAmount, PaymentDate, WhatWasPaymentFor
FROM Payments cross join
(select @SearchValue as sv) const
WHERE ParentID = @ParentID AND
(case when @SearchType = 'Dates' and ISDATE(const.sv) = 1
then (case when PaymentDate = CAST(const.sv AS datetime) then 'true' else 'false' end)
when @SearchType = 'Numbers' and ISNUMERIC(const.sv) = 1
then (case when PaymentAmount = cast(const.sv as Int) then 'true' else 'false' end)
when @SearchType = 'Everything Else'
then (case when WhatWasPaymentFor LIKE '%' + const.sv + '%' OR const.sv='ALL' then 'true' else 'false' end)
end) = 'true'
这是基于 gh9 并提取数据的。谢谢gh9:
DECLARE @SearchValue VARCHAR = 'Books'
DECLARE @ParentID INT = 3
DECLARE @PaymentDate DATETIME = NULL
DECLARE @PaymentAmount MONEY = NULL
SELECT ID, PaymentAmount, PaymentDate, WhatWasPaymentFor
FROM Payments
WHERE ParentID = @ParentID
AND (@paymentDate is null OR PaymentDate = @Paymentdate)
AND (@paymentAmount is null OR paymentAmount = @paymentAmount)
AND ((@SearchValue is null OR
(WhatWasPaymentFor LIKE '%' + @SearchValue + '%' OR @SearchValue='ALL'))
)