存储过程中的自动增量变量

问题描述 投票:0回答:1

我有一个程序可以保存答复调查的用户的答案。我的数据库有3个表格SurveyData,SurveyQuestions和SurveyAnswers。

SurveyData存储来自用户的数据

IdData || Name || Ocupation

SurveyQuestions有所有可用的问题

IdQuestion || Question
1          || question 1
2          || question 2 ...

和SurveyAnswers,存储用户给出的答复

IdData || IdQuestion || Answer

我的数据库中总共有10个问题,我想做的是将StoredProcedure插入IdQuestion列中的值(从1到10,并且当另一个用户答复再次从1到10重新开始该计数时]

这是我当前的SP

USE [Surveys]
GO
/****** Object:  StoredProcedure [usurvey].[InsertSurvey] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [usurvey].[InsertSurvey] @Name varchar(50), @Ocupation varchar(50), @replies varchar(2000)
as begin
DECLARE @idData int
declare @posreply int
declare @reply varchar(20)
    begin
    INSERT INTO SurveyData(Name,Ocupation)
    VALUES (@Name,@Ocupation)
    SET @idData=(SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY])

    end
    if (@replies <> '')
    begin
        while PATINDEX ('%|%', @replies) <> 0
        begin
            select @posreply = PATINDEX('%|%',@replies)
            select @reply = left(@replies,@posreply -1)
            insert into SurveyAnswers (idData, idQuestion, Answer)
            select @idData,ROW_NUMBER() OVER (order by (select null)),@reply
            select @replies = STUFF(@replies, 1, @posreply,'')
        end
    end
END

执行SP时

exec InsertarSurvey @Name = 'john', @Ocupation = 'teacher' , @respuestas = 'almost never|never|always|'

这是执行的结果

IdData || IdQuestion || Answer
1      || 1          || almost never
1      || 1          || never
1      || 1          || always

这是我想要得到的结果

IdData || IdQuestion || Answer
1      || 1          || almost never
1      || 2          || never
1      || 3          || always

如果其他人完成了调查

IdData || IdQuestion || Answer
1      || 1          || almost never
1      || 2          || never
1      || 3          || always
2      || 1          || never
2      || 2          || never
2      || 3          || almost always
sql-server stored-procedures auto-increment
1个回答
0
投票

代替循环,您可以结合使用STRING_SPLIT和ROW_NUMBER函数。

DECLARE @replies varchar(2000) = 'almost never|never|always|'
SELECT value, ROW_NUMBER() OVER (order by (select null)) FROM STRING_SPLIT(@replies,'|')
© www.soinside.com 2019 - 2024. All rights reserved.