Using a string that contains values ​​in a query

Using a string that contains values ​​in a query

So this probably sounds like a dumb question, but I never did that.

I have a line that looks like this ...

ValueID = 123, 234, 345, 466, 456

I also have a query that looks something like this:

 Select * from Tbl1 where SomeValue In (123,234,345, 466, 456)

So now I'm trying to do this ...

Select * from Tbl1 where someValue in (ValueID)

Something like that?

0
source share
4 answers

I think you want to use a dynamic query: -

is the next code help?

declare @ValueID varchar(200)
set @ValueID = '123, 234, 345, 466, 456'
exec ('Select * from Tbl1 where someValue in ('+ @ValueID +')')
+3
source

Your ValueID var should be a string.

ValueID = '123, 234, 345, 466, 456';

, , , , , SQL- String. , , @ahmed abdelqader .

declare @ValueID varchar(200)
set @ValueID = '123, 234, 345, 466, 456'
exec ('Select * from Tbl1 where someValue in ('+ @ValueID +')')
+1

.

.

DECLARE @MyList TABLE (Value VARCHAR(10))
INSERT INTO @MyList VALUES ('123')
INSERT INTO @MyList VALUES ('234')
[...]

SELECT *
FROM MyTable
WHERE MyColumn IN (SELECT Value FROM @MyList)

IN (T-SQL). , , , , . , , IN , . INT, VARCHAR INT .

+1

Using the CSV Splitter Feature by Jeff Moden:

create table v (ValueId varchar(8000))
insert into v values ('123, 234, 345, 466, 456');

create table t (someValue int);
insert into t values (345),(346)

select *
from t
where someValue in (
  select x.Item 
    from v
    cross apply (
        select Item 
        from [dbo].[delimitedsplit8K](v.ValueId,',')
        ) as x
    where x.Item <>''
    )

test setup: http://rextester.com/GRNWY13179

returns:

+-----------+
| someValue |
+-----------+
|       345 |
+-----------+

link for dividing lines:

0
source

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


All Articles