Let's say I have a table which contains a varchar field:
CREATE TABLE [MyTable] (
[MyId] varchar(3) NOT NULL,
.....
)
The [MyId] column contains sequential alphanum values like A1, A2... A99, B1, B2..B99, C1 and so on (up to Z99).
What I'd like to do is to extract rows from the table whose MyId field matches some specific prefixes... e.g. I'd like to fetch rows from the series A, C, P and X.
And I'd like to this with a sproc which will dynamically construct the query based on the prefix alphabets supplied in the argument.
I'm thinking about something like this...
CREATE PROCEDURE [dbo].[uspFilterMyTable]
@prefixArray varchar(max)
AS
... -- split individual characters from @prefixArray into an array
SELECT * FROM [MyTable]
WHERE
[MyId] LIKE ....
OR
[MyId] LIKE .... -- iterate all characters from @prefixArray
I think the main bulk of the stored procedure will resemble the following pseudo-code:
DECLARE @sql nvarchar(max)
-- iterate through all the characters
SET @sql = 'SELECT * FROM [MyTable] WHERE [MyId] LIKE ' + @charInTheArray + '%'
SET @sql = @sql + ' OR [MyId] LIKE ' + @nextCharInArray + '%'
EXEC (@sql)
The above proecedure will be called like this:
EXEC uspFilterMyTable("A,C,P,X")
... or perhaps like this (if it makes splitting the alphabets easier):
EXEC uspFilterMyTable("ACPX")
Any ideas? Pointers?
Update: OK, this is what I've come up with ([Split] function borrowed from Chhatrapati Sharma):
-- [MyTable] contains these rows: 'A7', 'A87', 'B16', 'C51', 'H99', 'X12'
-- the "input" parameter
DECLARE @prefixArray NVARCHAR(100)= 'H,A,C'
-- split the string into SQL wild-card patterns
DECLARE charCursor CURSOR FOR
select items + N'%' from dbo.Split(@prefixArray, ',')
OPEN charCursor;
DECLARE @pattern CHAR(2)
-- create temp table if necessary
IF NOT EXISTS(SELECT * FROM TEMPDB.SYS.TABLES WHERE NAME LIKE '#tmpTable%')
CREATE TABLE #tmpTable ([Id] VARCHAR(3) NOT NULL)
-- purge old data
DELETE FROM #tmpTable
FETCH NEXT FROM charCursor into @pattern
WHILE @@FETCH_STATUS = 0
BEGIN
--SELECT * INTO #tmpTable FROM [MyTable] WHERE [MyId] LIKE @pattern
Insert Into #tmpTable Select * FROM [MyTable] WHERE [MyId] LIKE @pattern
FETCH NEXT FROM charCursor into @pattern
END
CLOSE charCursor;
DEALLOCATE charCursor;
-- return the values
SELECT * FROM #tmpTable
It's ugly I know, but it works... any tips to improvise the code?