SQL Server:将查询结果存储到变量中

时间:2018-08-30 12:55:55

标签: sql sql-server sql-server-2012

我正在尝试将每个人的查询结果连接到一个变量中。 游标从#temp表中提取Columname并从PersonTable中提取数据

例如:对于PID = 1(FName:John LName:Hill HomeCountry = US HomeState = CH) 123JohnHillUSCH

  Person Table:

pid FName   LName   HomeCity    HomeState
1   Pascal    E    New York      NY
2   Steve     F    New York      NY

CREATE table #Temp
    ([Id] int,  [ColumnName] varchar(13))
;

INSERT INTO #Temp
    ([Id],[ColumnName])
VALUES
    (1,  'EID'),
    (2,  'FName'),
    (3,  'LName'),
    (4,  'HomeCountry'),
    (5,  'HomeState')
;

SELECT * FROM #Temp



SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
GO
ALTER  PROCEDURE [dbo].[up_Conv_GenerateResultsFromMappingTable]
@Param1 VARCHAR(30)
AS
SET NOCOUNT ON

DECLARE @ColName VARCHAR(100);
DECLARE @Result VARCHAR(MAX)

DECLARE @Cur as CURSOR;

SET @Cur = CURSOR FOR
SELECT columnName FROM #Temp

OPEN @Cur;
FETCH NEXT FROM @Cur INTO @ColName;

WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @query nvarchar(MAX)
PRINT @Param1;
SET @Query='SELECT '+@ColName+' FROM dbo.PERSON where PID='+@Param1+''  
PRINT @Query 
EXECUTE sp_executesql @Query
                  ,  N'@Param1 varchar(30)', 
                   @Param1 


FETCH NEXT FROM @Cur INTO @ColName;
END

CLOSE @Cur;
DEALLOCATE @Cur;

预期结果

1,1PascalENewYorkNY
2,2SteveFNewYorkNY

1 个答案:

答案 0 :(得分:2)

在SQL Server 2012+中,为什么不做

SELECT EID, CONCAT(EID, FName, LName, HomeCountry, HomeState) AS ConcatString, CreateDate
FROM Person

在SQL Server 2008R2及更低版本中,它必须是

SELECT EID, CAST(EID AS VARCHAR(20) + FName + LName + HomeCountry + HomeState AS ConcatString, CreateDate
FROM Person

如果要返回每个用户的结果,则可以对其进行参数化,然后分别从源中发送EID,或者可以使用光标...如果有的话绝对没有其他选择。如果要返回整个数据集,则可以直接使用该数据集中的数据。