我正在尝试在sql server 2008中编写存储过程。 我需要UserId(用户ID来自另一个表(dbo.UserSubjects))和UserName(来自dbo.UserDetails)获取用户(dbo.UserDetails中的所有列)。 我将始终拥有UserID,但并不总是拥有UserName。
所以现在我的问题是如何编写存储过程的if UserName为空,查询将仅由UserId搜索,如果UserName不为空 查询将使用UserId和UserName
进行搜索到目前为止,我写过:
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[GetUserBySubjectID](@ID int = NULL, @Name string)
AS
SET NOCOUNT ON
BEGIN TRY
IF @ID IS NULL
RAISERROR 400001 'User with given Subject ID does not exist'
ELSE
BEGIN
SELECT UD.*
FROM dbo.UserDetails UD , dbo.UserSubjects US
WHERE US.UserID = UD.UserID and US.SubjectID = @ID and UD.UserName = @Name
IF @@ROWCOUNT = 0
RAISERROR 400001 'User with given ID does not exist'
END
RETURN 0
END TRY
BEGIN CATCH
EXEC dbo.GetErrorInfo
RETURN 1
END CATCH
答案 0 :(得分:0)
只需在代码中添加另一个IF语句,以检查@Name
是否为NULL:
IF @Name IS NULL
BEGIN
...
WHERE US.UserID = UD.UserID and US.SubjectID = @ID
...
END
ELSE
BEGIN
...
WHERE US.UserID = UD.UserID and US.SubjectID = @ID and UD.UserName = @Name
...
可能感觉就像编写重复代码一样,但它的表现要比编写动态WHERE
子句好得多。