我正在编写一个客户搜索存储过程,其中有三个参数firstname, lastname, fathers name
都是varchar
我写的如下:
CREATE PROCEDURE [dbo].[SearchCustomer]
(
@p_FirstName varchar = NULL
,@p_LastName varchar = NULL
,@p_FatherFirstName varchar = NULL
)
AS
BEGIN
SET NOCOUNT ON
SELECT [CustomerID]
,[CustomerTitle]
,[FirstName]
,[MiddleName]
,[LastName]
,[FatherFirstName]
,[EmailId]
FROM [Customer]
WHERE [FirstName] LIKE COALESCE(@p_FirstName,'%')
OR [LastName] LIKE COALESCE @p_LastName,'%')
OR [FatherFirstName] LIKE COALESCE(@p_FatherFirstName,'%')
END
我正在使用可选参数,因为如果没有参数值,我需要在没有任何条件的情况下获得完整列表,但是当我只给出第一个名称时,我只需要那些匹配该条件的行而不是其余的,但现在它的列表全部< / p>
我猜这个问题就在OR附近
你能帮忙吗?
如果我将OR更改为AND
现在如果我把名字作为'abc'和姓氏和父亲名字黑......
我正在获取所有列表,包括'abc'作为名字..
我只需要名字为'abc'的行而不是其余的
答案 0 :(得分:1)
这将根据提交的参数过滤行:
CREATE PROCEDURE [dbo].[SearchCustomer]
(
@p_FirstName varchar(50) = NULL
,@p_LastName varchar(50) = NULL
,@p_FatherFirstName varchar(50) = NULL
)
AS
BEGIN
SET NOCOUNT ON
SELECT [CustomerID]
,[CustomerTitle]
,[FirstName]
,[MiddleName]
,[LastName]
,[FatherFirstName]
,[EmailId]
FROM [Customer]
WHERE [FirstName] LIKE COALESCE(@p_FirstName + '%', FirstName)
AND [LastName] LIKE COALESCE (@p_LastName + '%', LastName)
AND [FatherFirstName] LIKE COALESCE(@p_FatherFirstName + '%', FatherFirstName)
END
GO
答案 1 :(得分:0)
使用where子句,如下例所示。
WHERE (@p_FirstName='' or [FirstName] LIKE COALESCE(@p_FirstName,'%'))
OR (@p_LastName='' or [LastName] LIKE COALESCE @p_LastName,'%'))
OR (@p_FatherFirstName='' or [FatherFirstName] LIKE COALESCE(@p_FatherFirstName,'%'))
并使用以下语法设置所有参数''(如果它们为NULL)。
SET @p_FirstName=ISNULL(@p_FirstName,'')
答案 2 :(得分:0)
CREATE PROCEDURE [dbo].[SearchCustomer]
(
@p_FirstName varchar = NULL
,@p_LastName varchar = NULL
,@p_FatherFirstName varchar = NULL
)
AS
BEGIN
SET NOCOUNT ON
SELECT [CustomerID]
,[CustomerTitle]
,[FirstName]
,[MiddleName]
,[LastName]
,[FatherFirstName]
,[EmailId]
FROM [Customer]
WHERE [FirstName] LIKE COALESCE(@p_FirstName,'%')
OR (FirstName is NULL
AND [LastName] LIKE COALESCE(@p_LastName,'%')
AND [FatherFirstName] LIKE COALESCE(@p_FatherFirstName,'%'))
END
答案 3 :(得分:0)
CREATE PROCEDURE [dbo].[SearchCustomer]
(
@p_FirstName varchar(50) = NULL
,@p_LastName varchar(50) = NULL
,@p_FatherFirstName varchar(50) = NULL
)
AS
BEGIN
SET NOCOUNT ON
SELECT [CustomerID]
,[CustomerTitle]
,[FirstName]
,[MiddleName]
,[LastName]
,[FatherFirstName]
,[EmailId]
FROM [Customer]
WHERE ([FirstName] = @p_FirstName OR @p_FirstName IS NULL)
AND ([LastName] = @p_LastName OR @p_LastName IS NULL)
AND ([FatherFirstName] = @p_FatherFirstName OR @p_FatherFirstName IS NULL)
END