SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[func_SplitStringReturnSql]
(
@ArrayString NVARCHAR(50),
@FieldName NVARCHAR(30),
@FieldType NVARCHAR(10)
)
RETURNS NVARCHAR(255)
AS
BEGIN
DECLARE @Sql VARCHAR(255)
DECLARE @StartPos INT
DECLARE @EndPos INT
DECLARE @Delimiter VARCHAR(1)
DECLARE @SplitVal NVARCHAR(10)
SET @Sql = ''
SET @Delimiter = ','
SET @StartPos = 0
SET @EndPos = CHARINDEX(@Delimiter, @ArrayString, @StartPos)
-- !!! Array string needs to end with the seperator character to work right !!!
--------------------------------------------------------------------------------
WHILE ((@EndPos > 0) And (@StartPos < LEN(@ArrayString)))
BEGIN
SET @SplitVal = CONVERT(NVARCHAR(10), LTRIM(RTRIM(SUBSTRING(@ArrayString, @StartPos, @EndPos - @StartPos))))
IF (@StartPos > 0)
BEGIN
SET @Sql += ' OR '
END
IF (@FieldType = 'int')
BEGIN
SET @Sql += @FieldName + '=' + CONVERT(NVARCHAR(10), @SplitVal)
END
IF (@FieldType = 'char')
BEGIN
SET @Sql += @FieldName + '=''' + CONVERT(NVARCHAR(10), @SplitVal) + ''''
END
SET @StartPos = @EndPos + LEN(@Delimiter)
SET @EndPos = CHARINDEX(@Delimiter, @ArrayString, @StartPos)
END
RETURN
(
SELECT @Sql
)
END
DECLARE @AgeGroupArray NVARCHAR(50)
SET @AgeGroupArray = 'x,y,'
IF (LEN(@AgeGroupArray) > 0)
BEGIN
SET @SqlString = @SqlString + N'AND (' +
[dbo].[func_SplitStringReturnSql](@AgeGroupArray, '[P].[AgeGap]', 'char') +
N') '
END
-- RETURNS:
-- [P].[AgeGap]='x' OR [P].[AgeGap]='y'