我有三个字符串值,我在管道分隔符上拆分,我需要将这些值合并到一个表中。
我已经设置了一个函数来分割这些值并将它们放在三个单独的临时表中。
我需要在一个表中使用这些值。我怎么能这样做??
SET @QuestionData = '5|7|2'
SET @QuestionsDataCorrect = '0|1|0'
SET @QuestionsCount = '1|1|1'
DECLARE @QuestionsPrimaryTable Table (QuestionsId nvarchar(max))
INSERT INTO @QuestionsPrimaryTable
SELECT Item FROM SplitString(@QuestionData, '|')
DECLARE @QuestionsCorrectTemp Table (CorrectId nvarchar(max))
INSERT INTO @QuestionsCorrectTemp
SELECT Item FROM SplitString(@QuestionsDataCorrect, '|')
DECLARE @QuestionsCountTemp Table (CountId nvarchar(max))
INSERT INTO @QuestionsCountTemp
SELECT Item FROM SplitString(@QuestionsCount, '|')
select * from @QuestionsPrimaryTable
select * from @QuestionsCorrectTemp
select * from @QuestionsCountTemp
我的最终目标是拥有像这样的值
5 0 1
7 1 1
2 0 1
答案 0 :(得分:2)
您需要在结果集中包含项目编号,以便您可以使用它来加入数据。因此,您的函数也需要返回项目位置,然后您可以执行以下操作:
SET @QuestionData = '5|7|2'
SET @QuestionsDataCorrect = '0|1|0'
SET @QuestionsCount = '1|1|1'
DECLARE @QuestionsPrimaryTable Table (QuestionsId nvarchar(max), pos int)
INSERT INTO @QuestionsPrimaryTable
SELECT Item, ItemPos FROM SplitString(@QuestionData, '|')
DECLARE @QuestionsCorrectTemp Table (CorrectId nvarchar(max), pos int)
INSERT INTO @QuestionsCorrectTemp
SELECT Item, ItemPos FROM SplitString(@QuestionsDataCorrect, '|')
DECLARE @QuestionsCountTemp Table (CountId nvarchar(max), pos int)
INSERT INTO @QuestionsCountTemp
SELECT Item, ItemPos FROM SplitString(@QuestionsCount, '|')
select * from
@QuestionsPrimaryTable P
join @QuestionsCorrectTemp C on P.pos = C.pos
join @QuestionsCountTemp CO on P.pos = CO.pos
这假设所有这3个列表的项目总数相同。
答案 1 :(得分:1)
您可以向临时表添加标识列,然后使用此列上的连接创建新表。
首先添加标识列:
DECLARE @QuestionsPrimaryTable Table (Id INT IDENTITY(1,1), QuestionsId nvarchar(max))
INSERT INTO @QuestionsPrimaryTable
SELECT Item FROM SplitString(@QuestionData, '|')
DECLARE @QuestionsCorrectTemp Table (Id INT IDENTITY(1,1), CorrectId nvarchar(max))
INSERT INTO @QuestionsCorrectTemp
SELECT Item FROM SplitString(@QuestionsDataCorrect, '|')
DECLARE @QuestionsCountTemp Table (Id INT IDENTITY(1,1), CountId nvarchar(max))
INSERT INTO @QuestionsCountTemp
SELECT Item FROM SplitString(@QuestionsCount, '|')
然后声明一个新表,并使用以ID:
加入来插入其他三个表中的所有值DECLARE @QuestionsAll Table (QuestionsId nvarchar(max), CorrectId nvarchar(max), CountId nvarchar(max))
INSERT INTO @QuestionsAll (QuestionsId, CorrectId, CountId)
SELECT prim.QuestionsId, corr.CorrectId, cnt.CountId
FROM @QuestionsPrimaryTable prim
INNER JOIN @QuestionsCorrectTemp corr ON prim.Id = corr.Id
INNER JOIN @QuestionsCountTemp cnt ON prim.Id = count.Id