TSQL String modify

2019-01-15 23:49发布

问题:

I have a problem with string. I have a variable @Rights which looks like 'ASD,ZXC,QWE,IOP,JKL' What I need to do is use this string in

SELECT * FROM dbo.Example
WHERE Rights IN (@Rights)

Problem is that I need to convert:

'ASD,ZXC,QWE,IOP,JKL'

to:

'ASD','ZXC','QWE','IOP','JKL'

How can I do this?

回答1:

you can create a split function

CREATE FUNCTION [dbo].[Split]
(
    @String NVARCHAR(4000),
    @Delimiter NCHAR(1)
)
RETURNS TABLE
AS
RETURN
(
    WITH Split(stpos,endpos)
    AS(
        SELECT 0 AS stpos, CHARINDEX(@Delimiter,@String) AS endpos
        UNION ALL
        SELECT endpos+1, CHARINDEX(@Delimiter,@String,endpos+1)
            FROM Split
            WHERE endpos > 0
    )
    SELECT 'Id' = ROW_NUMBER() OVER (ORDER BY (SELECT 1)),
        'Data' = SUBSTRING(@String,stpos,COALESCE(NULLIF(endpos,0),LEN(@String)+1)-stpos)
    FROM Split
)
GO

and after you can convert the string in a temp table

DECLARE @Rights NVARCHAR(128)
SET @Rights = 'ASD,ZXC,QWE,IOP,JKL'
SELECT *
INTO #Temp
FROM dbo.Split(@Rights , ',')

and after you can use it in your query like this

SELECT * FROM dbo.Example
WHERE Rights IN (SELECT Data FROM #Temp)


回答2:

You can try like this:

DECLARE @xml xml, @str varchar(100), @delimiter varchar(10)
SET @str = 'ASD,ZXC,QWE,IOP,JKL'
SET @delimiter = ','
SET @xml = cast(('<X>'+replace(@str, @delimiter, '</X><X>')+'</X>') as xml)
SELECT C.value('.', 'varchar(10)') as value FROM @xml.nodes('X') as X(C)

SQL DEMO



回答3:

You can use Dynamic SQL:

LiveDemo

-- sample data
CREATE TABLE #Example(ID INT IDENTITY(1,1), Rights VARCHAR(100));
INSERT INTO #Example VALUES ('ASD'), ('ABC'), ('IOP');


DECLARE @Rights NVARCHAR(MAX) = 'ASD,ZXC,QWE,IOP,JKL';
DECLARE @sql NVARCHAR(MAX) = 
  N'SELECT * 
   FROM #Example
   WHERE Rights IN (''<placeholder>'')';

SET @sql = REPLACE(@sql, '<placeholder>', REPLACE(@Rights, ',', ''','''));

-- SELECT @sql; -- for debug

EXEC dbo.sp_executesql
    @sql;

But you should reconsider using Table Valued Parameter instead.