如何有条件地执行WHERE子句?

时间:2011-06-24 06:39:38

标签: sql sql-server tsql sql-server-2008 stored-procedures

嗨,我有一个存储过程:

ALTER PROCEDURE [dbo].[spGetStaffsAndClients]
(
    @staffIds nvarchar(1024)
)
AS
BEGIN

    declare @Address varchar (100)
    declare @Apartment varchar (100)
    declare @City varchar (100)
    declare @State varchar (10)
    declare @Zip varchar (10)
    declare @County varchar (100)
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here

    /* Get Client's Residence */

    select dbo.GetClientFullName(s.FirstName, s.MiddleInit, s.LastName) StaffName, 
    dbo.GetStaffTitlesById(s.Id) StaffTitle,
    dbo.GetClientFullName(c.FirstName, c.MiddleInit, c.LastName) ClientName, 
    dbo.GetAddressByEntityNameAndId('Client', c.Id) ClientAddress

    from ClientStaff cs 
    left outer join Staff s on cs.StaffId = s.Id 
    left outer join Client c on cs.ClientId = c.Id

    where s.Id in ( SELECT convert(int,Value) FROM dbo.Split(@staffIds, ','))

END

我希望where子句仅在@staffIds <> ''时执行,否则不执行。

请指导我如何做到这一点。

2 个答案:

答案 0 :(得分:2)

where 
    @staffIds = '' or 
    @staffIds is null or 
    s.Id in ( SELECT convert(int,Value) FROM dbo.Split(@staffIds, ','))

答案 1 :(得分:0)

您可以先尝试编写查询,然后将其存储在字符串中。

然后使用EXEC执行字符串。