将多于 1 行的输出设置为 1 个变量

SET more than 1 row output into 1 variable

我希望能够在单个变量中保存来自 SELECT 查询的不止 1 个输出。

目前我正在像这样收集我需要的数据:

DECLARE @something1 VARCHAR(MAX)
DECLARE @something2 VARCHAR(MAX)
DECLARE @something3 VARCHAR(MAX)

SET @something1 = (
  SELECT 
     Custom AS 'XXL Format' 
  FROM 
     tblData 
  WHERE 
     ID = 1);

SET @something2 = (
  SELECT 
     Custom.value('(/Individual/text())[1]', 'varchar(MAX)') AS 'Non XML Format' 
  FROM 
     tblData 
  WHERE 
     ID = 1)

SET @something3 = (
  SELECT 
     tbl1.paper, 
     tbl2.type 
  FROM 
     tblData AS tbl1 
  JOIN tblData2 tbl2 
     ON tbl1.ID = tbl2.ID 
  WHERE 
     ID = 1);

我有以下演示,展示了我想做的事情

DECLARE @tester VARCHAR(MAX)

SET @tester = (
  SELECT 
     tbl1.Custom AS 'XXL Format',
     tbl1.Custom.value('(/Individual/text())[1]', 'varchar(MAX)') AS 'Non XML Format'
     tbl1.paper, 
     tbl2.type 
  FROM 
     tblData AS tbl1 
  JOIN tblData2 tbl2 
     ON tbl1.ID = tbl2.ID 
  WHERE 
     ID = 1);

我得到以下错误:

Only one expression can be specified in the select list when the subquery is not introduced with EXISTS

两个演示都可以找到here

我已经尝试将变量设置为“table”并像这样存储数据,但这似乎也无法正常工作[我确定我做错了什么 - 这可能是回答我要问的这个问题]

我怎样才能对上述查询输出的所有内容使用 1 个变量?

您的错误是子查询返回了多个值。如果您不关心分配哪个值,则可以使用 top

SET @tester = (SELECT TOP (1) description FROM ForgeRock); 

你必须 return 只有一个值你可以尝试 toplimit 比如 SET @tester = (SELECT TOP 1 description FROM ForgeRock);SET @tester = (SELECT description FROM ForgeRock LIMIT 1);

所以我想我将变量设置为临时“table”是正确的。我终于让它满足我的需要!

DECLARE @tmpTbl table (_xml, _parsedXML, _paper, _type)

INSERT INTO @tmpTbl 
  SELECT 
     tbl1.Custom AS 'XML Format',
     tbl1.Custom.value('(/Individual/text())[1]', 'varchar(MAX)') AS 'Non XML Format',
     tbl1.paper, 
     tbl2.type  
  FROM 
     tblData AS tbl1 
  JOIN tblData2 AS tbl2 
     ON tbl1.ID = tbl2.ID 
  WHERE 
     ID = 1;

DECLARE @something1 VARCHAR(MAX) = (SELECT _xml FROM @tmpTbl);
DECLARE @something2 VARCHAR(MAX) = (SELECT _parsedXML FROM @tmpTbl);
DECLARE @something3 VARCHAR(MAX) = (SELECT _paper FROM @tmpTbl);
DECLARE @something4 VARCHAR(MAX) = (SELECT _type FROM @tmpTbl);

DELETE FROM @tmpTbl --Not really needed but nice to be offical :)

以上将值存储到一个地方。虽然它不在 1 个变量内,但我想必须创建一个临时 table 对于 database/performance...

来说并不是那么糟糕