我基本上试图将查询的输出存储在变量中,但是收到错误消息
子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。
--DECLARE @companystring varchar(max)= '867343,867358,867443,867458,867543'
DECLARE @companystring varchar(max)
set @companystring = (SELECT DISTINCT Top 1000(mc.companyId) FROM ciqMarketCap mc
JOIN ciqCompany c ON c.companyid = mc.companyid
WHERE c.companyStatusTypeId NOT IN (5,6) AND c.companyTypeId IN (1,4))
select
ci.id
into #companyId
from dbo.splitstring(@companystring) ci
有人可以告诉我这是什么问题吗?
答案 0 :(得分:1)
如果我理解你正确而你需要将列数据转换为字符串,则可以使用下一个查询 -
DECLARE @companystring nvarchar(max)
SELECT TOP 1000 @companystring = coalesce(@companystring+';','') + CAST( mc.companyId AS nvarchar)
FROM ciqMarketCap mc
JOIN ciqCompany c ON c.companyid = mc.companyid
WHERE c.companyStatusTypeId NOT IN (5,6) AND c.companyTypeId IN (1,4)
SELECT @companystring
答案 1 :(得分:1)
首先,将大型数据集存储到nvarchar / varchar变量中并不理想。 适当的步骤是创建临时表变量。请参阅下面的编辑查询:
DECLARE @companystring TABLE(companyId nvarchar(max));
INSERT INTO @companystring(companyId)
SELECT
DISTINCT Top 1000(mc.companyId)
FROM ciqMarketCap mc
JOIN ciqCompany c ON c.companyid = mc.companyid
WHERE c.companyStatusTypeId NOT IN (5,6)
AND c.companyTypeId IN (1,4);
select ci.companyId into #companyId from @companystring ci;