2

我有以下查询可以正常工作。

SELECT ui.userID, 
    ui.lockedInd, 
    ui.lockedBy, 
    ui.lockedReason, 
    ui.updatedDtTm,
    ui.updatedBy,
    ua.password,
    ua.updatedDtTm,
    ua.updatedBy 
FROM userInfo ui 
JOIN userAuthentication ua 
    ON ui.userinfoseqid = ua.userinfoseqid
WHERE ui.userID IN (
    'userOne',
    'userTwo'
)

我想将用户名放入顶部声明的变量中。我有点困惑如何创建变量并添加到它,因为我总是只使用一个值完成变量。须藤代码如下

DECLARE @userIDs
SET @userIDs = "'userOne', 'userTwo'"

SELECT ui.userID, 
    ui.lockedInd, 
    ui.lockedBy, 
    ui.lockedReason, 
    ui.updatedDtTm,
    ui.updatedBy,
    ua.password,
    ua.updatedDtTm,
    ua.updatedBy 
FROM userInfo ui 
JOIN userAuthentication ua 
    ON ui.userinfoseqid = ua.userinfoseqid
WHERE ui.userID = @userIDs
4

2 回答 2

2

使用表变量应该适合您。

DECLARE @UserIDS TABLE 
(
    UserId VARCHAR(40)
)

INSERT INTO @UserIDS
(
UserId
)
SELECT 'UserOne'
UNION ALL SELECT 'UserTwo'
UNION ALL SELECT 'UserThree'

SELECT ui.userID, 
    ui.lockedInd, 
    ui.lockedBy, 
    ui.lockedReason, 
    ui.updatedDtTm,
    ui.updatedBy,
    ua.password,
    ua.updatedDtTm,
    ua.updatedBy 
FROM userInfo ui 
JOIN userAuthentication ua 
    ON ui.userinfoseqid = ua.userinfoseqid
WHERE ui.userID IN @UserIDS
于 2013-02-15T22:00:33.247 回答
2

您可以使用临时表,有更多信息:http ://www.simple-talk.com/sql/t-sql-programming/temporary-tables-in-sql-server/

例如,创建一个表变量:

DECLARE @UserIDs TABLE (ID nvarchar(50))
INSERT INTO @UserIDs VALUES ('userOne'), ('userTwo')

SELECT ui.userID
FROM userInfo ui 
JOIN userAuthentication ua 
    ON ui.userinfoseqid = ua.userinfoseqid
WHERE ui.userID IN (SELECT ID FROM @UserIDs)
于 2013-02-15T22:04:54.567 回答