我想将动态变量中的多个记录插入到临时表中,但是我无法获得成功。 INSERT
无法获得成功。你有想法怎么做吗?
我收到了以下错误:A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations.
代码的一部分:
-- Creating temp table
CREATE TABLE #tempTest
(
one DATE,
two ID,
three NVARCHAR(60)
)
DECLARE @test NVARCHAR(MAX)
-- Selecting 3 records (Date, Id, Email) to insert into temp table
SELECT @test = Date, Id, Email --throws error in this line
FROM (SELECT [Date], [Id], [Email]
FROM (
SELECT ROW_NUMBER() OVER (ORDER BY FI.Id ASC) AS 'RowNum', CONVERT(DATE, FormV.[DateUpdated]) AS [Date], FI.Id AS [Id]
FROM FormI AS FI
INNER JOIN FormV AS FormV
ON FI.FormVId = FormV.Id
INNER JOIN NavArt AS NA
ON FI.ArtId = NA.Id
WHERE FI.WorkShiftId = 10
) withRownNum
WHERE RowNum = 1
) a
-- Here I'm trying to insert these records to temp table, but unsuccessfully
INSERT INTO #tempTest VALUES(@colsConversion)
答案 0 :(得分:0)
问题在于,您不能在select
中为变量分配一些列,但不能将所有列分配给变量。我不知道你为什么要分配任何内容,但你也可能有@id
和@email
的变量。
如果你想创建一个临时表,为什么不这样做呢?
SELECT [Date], [Id], [Email]
INTO #temptest
FROM (
SELECT ROW_NUMBER() OVER (ORDER BY FI.Id ASC) AS RowNum, CONVERT(DATE, FormV.[DateUpdated]) AS [Date], FI.Id AS [Id]
FROM FormI AS FI
INNER JOIN FormV AS FormV
ON FI.FormVId = FormV.Id
INNER JOIN NavArt AS NA
ON FI.ArtId = NA.Id
WHERE FI.WorkShiftId = 10
) withRownNum
WHERE RowNum = 1;
注意:编写此子查询可能更简单(例如使用top
),但这是另一个问题的答案。
答案 1 :(得分:0)
您不需要变量。试试这个:
CREATE TABLE #tempTest
(
one DATE,
two ID,
three NVARCHAR(60)
)
INSERT INTO #tempTest
SELECT Date, Id, Email
FROM (SELECT [Date], [Id], [Email]
FROM (
SELECT ROW_NUMBER() OVER (ORDER BY FI.Id ASC) AS 'RowNum', CONVERT(DATE, FormV.[DateUpdated]) AS [Date], FI.Id AS [Id]
FROM FormI AS FI
INNER JOIN FormV AS FormV
ON FI.FormVId = FormV.Id
INNER JOIN NavArt AS NA
ON FI.ArtId = NA.Id
WHERE FI.WorkShiftId = 10
) withRownNum
WHERE RowNum = 1
) a