简体   繁体   English

从表中选择@variable in(表列)

[英]select from table where @variable in(table column)

could u please correct this sqlserver query : 您能否更正此sqlserver查询:

select * from messages where @DepartID In(MsgTo)

@DepartID is a session variable that contains the Department ID. @DepartID是包含Department ID的会话变量。 MsgTo is a column in messages table that contains list of values , ex. MsgTo是邮件表中的一列,其中包含值列表,例如。 : '12','10','13','25' .. etc :'12','10','13','25'..等

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? 您是否在SQL中声明了@DepartID变量? You need to make a comparison to an existing column in your WHERE clause. 您需要与WHERE子句中的现有列进行比较。 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. 如果部门ID是SQL中的文本类型的列,则必须在输入中使用单引号。 You can use single quotes anyways in integers like IDs when you query them with an "IN" statement and it will work anyways. 当您使用“ IN”语句查询单引号时,无论如何都可以使用整数(例如ID),单引号仍然可以使用。 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. 因此,如果用值替换@DepartID变量,然后执行该语句,它将返回[MsgTo]列等于@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: 如果要传递多个@DepartID,则必须使用变量将逗号分隔的文本列表传递给“ IN”子句,如下例所示:

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: 我不确定您用来执行SQL的语言,但是如果这样做不起作用,请尝试将SQL语句封装在EXEC()中,如下所示:

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: 如果您的MsgTo列包含值的字符串列表,并且您想在其中搜索单个@DepartID,请使用以下代码:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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