1

In my table id column's datatype is int.

And I have a list of items' ids to be selected.

So, here is some piece of my code:

DECLARE @user_list
SELECT @user_list=(
SELECT user_list
FROM sometable
WHERE rowNum=xxx
);
SELECT *
FROM anotherTable
WHERE user_id IN(@user_list)

but it doesn't work, the error msg like :

can't convert varchar to int

Thanks!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
MangMang
  • 427
  • 1
  • 5
  • 17
  • 2
    Is `user_list` a comma separated string? – Martin Smith Aug 20 '12 at 08:10
  • yes, it's a comma separated string in a varchar(MAX) column – MangMang Aug 20 '12 at 08:12
  • 1
    The `WHERE id IN (...)` expects a **list of (several) `int`** values, while you're passing in a **single string** that contains a list of int... that is not the same thing and they're not compatible. You need to **extract** those ints from the string and pass them in as a list of `int` – marc_s Aug 20 '12 at 08:13
  • i see, but i'm wondering how can i achieve my purpose? – MangMang Aug 20 '12 at 08:14

4 Answers4

7

You can Create a Split function and that will be use when you want.

CREATE FUNCTION [dbo].[Split]
(   
    @List nvarchar(max),
    @SplitOn nvarchar(1)
)
RETURNS @RtnValue table (
    Id int identity(1,1),
    Value nvarchar(max)
)
AS
BEGIN
    While (Charindex(@SplitOn,@List)>0)
    Begin 
        Insert Into @RtnValue (value)
        Select 
            Value = ltrim(rtrim(Substring(@List,1,Charindex(@SplitOn,@List)-1))) 
        Set @List = Substring(@List,Charindex(@SplitOn,@List)+len(@SplitOn),len(@List))
    End 

    Insert Into @RtnValue (Value)
    Select Value = ltrim(rtrim(@List))

    Return
END

after that you can call the function in your query as below.

SELECT * FROM anotherTable WHERE user_id IN(dbo.split(@user_list,','))

Otherwise, you have to use dynamic query.

Nitin Vijay
  • 1,414
  • 12
  • 28
0

you can use dynamic sql

exec('
SELECT *
FROM anotherTable
WHERE user_id IN('+@user_list+')')
Joe G Joseph
  • 23,518
  • 5
  • 56
  • 58
0

If you make @user_list a table variable, you can join or filter against it like any other table

 declare @user_list table (id int)
 insert @user_list(id)
 SELECT user_list 
 FROM sometable 
 WHERE rowNum=xxx 


 SELECT * 
 FROM anotherTable 
 WHERE user_id IN(select Id from @user_list) 
podiluska
  • 50,950
  • 7
  • 98
  • 104
0

Just use a table variable, which allows you to add normal word into a variable:

DECLARE @user_list AS TABLE (user_id int NOT NULL);

INSERT @user_list
SELECT user_list
FROM sometable
WHERE rowNum=xxx;

SELECT *
FROM anotherTable
WHERE user_id IN (SELECT user_id FROM @user_list)
Lucero
  • 59,176
  • 9
  • 122
  • 152