【问题标题】:Auto increment variable inside a stored procedure存储过程中的自动递增变量
【发布时间】:2020-06-22 17:10:49
【问题描述】:

我有一个程序可以保存回复调查的用户的答案。我的数据库有 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?
  • 你需要保持回复的顺序吗?

标签: sql-server stored-procedures auto-increment


【解决方案1】:

您可以将 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,'|')

【讨论】:

    猜你喜欢
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    • 2015-10-24
    • 2019-06-17
    • 1970-01-01
    相关资源
    最近更新 更多