简体   繁体   中英

select from table where @variable in(table column)

could u please correct this sqlserver query :

select * from messages where @DepartID In(MsgTo)

@DepartID is a session variable that contains the Department ID. MsgTo is a column in messages table that contains list of values , ex. : '12','10','13','25' .. etc

i used this code :

cmd.CommandText = "select * from messages where @DepartID IN(MsgTo)"
cmd.Parameters.AddWithValue("@DepartID ", session("DepartID")) ' = 12 for example

Dim da As New SqlDataAdapter(cmd)
Dim dt As New DataTable
da.Fill(dt)
lbmsg.text = dt.Rows.Count.ToString ' returns 0 rows

sorry for my poor english

I think you're just having some syntax trouble. Have you declared the @DepartID variable in SQL? You need to make a comparison to an existing column in your WHERE clause. Like:

SELECT [ColumnName]
FROM [Table]
WHERE [ColumnName] = Value

If your department ID is a text-type column in SQL, you'll have to use single quotes on your input. You can use single quotes anyways in integers like IDs when you query them with an "IN" statement and it will work anyways. Try this:

SELECT *
FROM [messages]
WHERE [MsgTo] = @DepartID

So if you replace your @DepartID variable out with your value and then execute the statement, it will return all information for each row where your [MsgTo] column equals your @DepartID.

If you are passing multiple @DepartIDs, then you would have to pass a comma-delimited text list to the "IN" clause with your variable like the example below:

SELECT *
FROM [messages]
WHERE [MsgTo] IN ('1','5','3','12','30')

--Example where @DepartID = '1','5','3','12','30'

I'm not sure what language you're using to execute the SQL, but if this doesn't work, try encapsulating your SQL statement within an EXEC() like below:

EXEC(
    SELECT *
    FROM [messages]
    WHERE [MsgTo] = @DepartID
)

If your MsgTo column contains a string list of values and you want to search through it for a single @DepartID, then use this code:

DECLARE @DepartID as INT; SET @DepartID = 12; --Hard coded example

SELECT *
FROM [messages]
WHERE [MsgTo] LIKE ('%,'''+@DepartID+''',%')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM