SQL变量仅保留返回的最后一个结果

时间:2019-03-17 13:10:11

标签: sql-server variables stored-procedures

以下语句存储并打印返回的最后结果。如何存储两个值?

表名:UserGroupBranchMapping

UserId      username           IsActive CountryName    AccessType
----------- ------------------ -------- -------------  ------------
140         demo1@demo1.com    1        SOUTH AFRICA   2
140         demo1@demo1.com    1        BOTSWANA       1 

SQL语句:

DECLARE @AccessType VARCHAR(100);
DECLARE @username NVARCHAR(MAX);
DECLARE @countryName NVARCHAR(MAX);
DECLARE @countryId VARCHAR(100);

SET @username = 'demo1@demo1.com,demo2@demo1.com';
SET @countryName = 'SOUTH AFRICA,BOTSWANA';

SELECT @AccessType = ugbm.AccessType, @countryId = ugbm.Countryid
FROM UserGroupBranchMapping ugbm
INNER JOIN Users usr ON usr.id = ugbm.UserId
INNER JOIN Country con ON con.id = ugbm.countryid
WHERE usr.UserName IN (SELECT item
                       FROM dbo.SplitString(@username, ','))
  AND con.countryName IN (SELECT item
                          FROM dbo.SplitString(@countryName, ','))
  AND ugbm.IsActive = 1;

PRINT @AccessType, @countryId

1 个答案:

答案 0 :(得分:1)

如Larnu所说,标量变量一次保持1(一个)值。当查询执行到达批处理命令的末尾时(很可能您使用默认命令GO),该变量将自动销毁,这意味着将丢失该点之前保持的值。

如果要同时将更多值保存​​到多个列中,则应使用表变量。

您可以使用以下内容:

DECLARE @UserGroupBranchMapping TABLE(
UserId int,
username nvarchar(200),
isActive bit,
CountryName nvarchar(200),
AccessType int
)


INSERT INTO @UserGroupBranchMapping (UserId, username, isActive, CountryName, AccessType)
VALUES(140, N'demo1@demo1.com', 1, N'SOUTH AFRICA', 2), (140, N'demo1@demo1.com', 1, N'BOTSWANA', 1)

以下SELECT语句将产生以下结果:

SELECT * 
FROM @UserGroupBranchMapping

UserId  username        isActive    CountryName   AccessType
------------------------------------------------------------
140     demo1@demo1.com    1        SOUTH AFRICA      2
140     demo1@demo1.com    1        BOTSWANA          1

请注意,表变量与标量变量具有相似的行为,这意味着当它到达批处理命令时,它将丢失所有值。