Sorry for the long post, but most of it is code spelling out my scenario:
I'm trying to execute a dynamic query (hopefully through a stored proceedure) to retrieve results based on a variable number of inputs.
If I had a table:
(dbo).(People)
ID Name Age
1 Joe 28
2 Bob 32
3 Alan 26
4 Joe 27
I want to allow the user to search by any of the three columns, no problem:
DECLARE @ID int, @Name nvarchar(25), @Age int
SET @ID = 1
SET @Name = 'Joe'
SET @Age = null
SELECT *
FROM dbo.People
WHERE
(ID = @ID or @ID is null) AND
(Name like @Name or @Name is null) AND
(Age = @Age or @Age is null)
And I retrieve the result that I want.
Now, if I want to search for multiple fields in a column, I can do that no problem:
DECLARE @text nvarchar(100)
SET @text = '1, 3'
DECLARE @ids AS TABLE (n int NOT NULL PRIMARY KEY)
--//parse the string into a table
DECLARE @TempString nvarchar(300), @Pos int
SET @text = LTRIM(RTRIM(@text))+ ','
SET @Pos = CHARINDEX(',', @text, 1)
IF REPLACE(@text, ',', '') <> ''
BEGIN
WHILE @Pos > 0
BEGIN
SET @TempString = LTRIM(RTRIM(LEFT(@text, @Pos - 1)))
IF @TempString <> '' --just: IF @TempString != ''
BEGIN
INSERT INTO @ids VALUES (@TempString)
END
SET @text = RIGHT(@text, LEN(@text) - @Pos)
SET @Pos = CHARINDEX(',', @text, 1)
END
END
SELECT *
FROM dbo.People
WHERE
ID IN (SELECT n FROM @ids)
Now, my issue is I can't seem to figure out how to combine the two since I can't put:
WHERE
(Name like @Name or @Name is null) AND
(Id IN (SELECT n FROM @ids) or @ids is null)
Because @ids will never be null (since it's a table)
Any help would be greatly appreciated!
Thanks in advance...and let me know if I can clarify anything