TSQL using template in where clause with dynamic sql

It seems that using LIKE in a wildcard condition and variable inside dynamic sql does not work, although it does not give an error. Here is an example.

The code column has values ​​such as A0B01C02, A0B02C2D05, A0B02C2D05, etc., and I'm trying to match rows containing a subset of type "B1". When I do this, it works and returns the results as expected.

set @sql='select * from table where code like ''%B01%'''
exec sp_executesql @sql

If I rigidly set the value of the set @code = 'B01' variable and change the sql operator to concatenate quotes and wildcards:

set @sql='select * from table where code like ' +''''+ '%'+@code + '%' + ''''
exec sp_executesql @sql

This returns the results as expected, but I had to hard code the variable. However, when I need to make a match using a variable for B01 and that the variable is set using the select statement, I get no results. I define nvarchar as follows:

set @code=(select top 1 code from anotherTable where USERID=@PersonId)

I confirmed that the above select statement returns the expected code. There is no error, but the request is successful. Am I missing something in the syntax for the where clause?

+3
source share
2 answers

http://ask.sqlservercentral.com/questions/275/dynamic-where-clause-how-can-i-use-a-variable-in-an-in-predicate/312#312
, Parse By Comma.

/*****************************************************************
**** Parse A Comma Delimited String Into A Table
*****************************************************************/
ALTER  FUNCTION [dbo].[ParseByComma] (
    @String VARCHAR(600) )
RETURNS @TblSubString TABLE
(
    VarSubString VARCHAR(50)
)
AS
BEGIN
    DECLARE @intPos INT,
            @SubStr VARCHAR(50)

    -- Remove All Spaces
    SET @String = REPLACE(@String, ' ','')
    -- Find The First Comma
    SET @IntPos = CHARINDEX(',', @String)
    -- Loop Until There Is Nothing Left Of @String
    WHILE @IntPos > 0
    BEGIN
        -- Extract The String
        SET @SubStr = SUBSTRING(@String, 0, @IntPos)
        -- Insert The String Into The Table
        INSERT INTO @TblSubString (VarSubString) VALUES (@SubStr)
        -- Remove The String & Comma Separator From The Original
        SET @String = SUBSTRING(@String, LEN(@SubStr) + 2, LEN(@String) - LEN(@SubStr) + 1)
        -- Get The New Index To The String
        SET @IntPos = CHARINDEX(',', @String)
    END
    -- Return The Last One
    INSERT INTO @TblSubString (VarSubString) VALUES (@String)
RETURN
END
0

SQL Server , , ?

set @sql = 'SELECT * FROM table WHERE UPPER (code) LIKE' '%' '|| (UPPER (COALESCE (' '' || @code || '' ', code)) ||' '%' '' exec sp_executesql @sql

,

0

Source: https://habr.com/ru/post/1721324/


All Articles