我使用存储过程在我的数据库中搜索并在参数上过滤结果,我需要过滤未知的多个参数。
如何编写处理此问题的存储过程?
这是我的存储过程:
CREATE PROCEDURE ComplaintRefListOnDistrict
@District nvarchar(max) = ''
AS
BEGIN
SET NOCOUNT ON;
SELECT
ComplaintFullID, CustomerName, Customer_Address, CustomerEmail,
Date, ContractID, CustomerPhoneNumber,ID, Complaintreference_ID, State
FROM
dbo.ComplaintsSmartObject
LEFT JOIN
dbo.UsersDistricts ON dbo.UsersDistricts.District = dbo.ComplaintsSmartObject.District
WHERE
(dbo.UsersDistricts.District = @District)
END
GO
谢谢!
答案 0 :(得分:1)
首先添加一个辅助函数,它将传递给它的字符串拆分成行。
CREATE FUNCTION SplitString
(
@string NVARCHAR(MAX),
@delimiter CHAR(1)
)
RETURNS
@output TABLE(Data NVARCHAR(MAX))
BEGIN
DECLARE @start INT, @end INT
SELECT @start = 1, @end = CHARINDEX(@delimiter, @string)
WHILE @start < LEN(@string) + 1
BEGIN
IF (@end = 0) SET @end = LEN(@string) + 1
INSERT INTO @output (Data) VALUES(SUBSTRING(@string, @start, @end - @start))
SET @start = @end + 1
SET @end = CHARINDEX(@delimiter, @string, @start)
END
RETURN
END
现在一切都很简单。使用SQL IN
运算符:
CREATE PROCEDURE ComplaintRefListOnDistrict
@District nvarchar(max) = ''
AS
BEGIN
SET NOCOUNT ON;
SELECT
ComplaintFullID, CustomerName, Customer_Address, CustomerEmail,
Date, ContractID, CustomerPhoneNumber,ID, Complaintreference_ID, State
FROM
dbo.ComplaintsSmartObject
LEFT JOIN
dbo.UsersDistricts ON dbo.UsersDistricts.District = dbo.ComplaintsSmartObject.District
WHERE
(dbo.UsersDistricts.District IN (SELECT Data FROM dbo.SplitString(@District, ',')))
END
HTH。
答案 1 :(得分:0)
CREATE PROCEDURE ComplaintRefListOnDistrict
(
@District nvarchar(max) = NULL
)
AS
BEGIN
SET NOCOUNT ON;
SELECT
CSC.ComplaintFullID, CSC.CustomerName, CSC.Customer_Address, CSC.CustomerEmail,
CSC.Date, UD.ContractID, UD.CustomerPhoneNumber,UD.ID, UD.Complaintreference_ID, UD.State
FROM
dbo.ComplaintsSmartObject CSC
LEFT JOIN dbo.UsersDistricts UD
ON UD.District = CSC.District
WHERE
(
UD.District LIKE '%' + @District + '%'
OR @District IS NULL
OR @District = ''
)
ORDER BY CSC.ComplaintFullID,
CSC.CustomerName,
CSC.Customer_Address,
CSC.CustomerEmail,
CSC.Date, UD.ContractID, UD.CustomerPhoneNumber,UD.ID, UD.Complaintreference_ID, UD.State
END
GO
答案 2 :(得分:0)
您可以创建一个WHERE子句,使用unknown参数或检查它是否为null
WHERE (dbo.UsersDistricts.District = @District OR District IS NULL)
AND (SomeOtherColumn = @OtherParameter OR OtherParameter IS NULL)
等等。
答案 3 :(得分:0)
我告诉我要使用这种动态SQL。
CREATE PROCEDURE ComplaintRefListOnDistrict
@District nvarchar(max) = ''
AS
BEGIN
SET NOCOUNT ON;
declare @sql nvarchar(max)
set @sql = 'SELECT
ComplaintFullID, CustomerName, Customer_Address, CustomerEmail,
Date, ContractID, CustomerPhoneNumber,ID, Complaintreference_ID, State
FROM
dbo.ComplaintsSmartObject
LEFT JOIN
dbo.UsersDistricts ON dbo.UsersDistricts.District = dbo.ComplaintsSmartObject.District
WHERE
(dbo.UsersDistricts.District in (' + @District + ') )'
EXEC sp_executesql @sql
END