复制身份并将其放到另一个表中

时间:2013-07-10 05:56:11

标签: sql sql-server sql-server-2008

美好的一天!我的存储过程遇到问题,这是我的代码:

INSERT INTO dbo.CS_RefQuestionChoice(ChoiceDescription, QuestionID, RatingID, SetID)

SELECT @choice, @@IDENTITY,@ratingid,1 FROM CS_RefQuestions

代码运行顺利,但我遇到了麻烦,因为它在我的数据库中保存了75条记录,它应该只保存一条,我想要执行的只是当我保存另一个选择时,它应该也保存了出于关系目的,CS_RefQuestions的最新主键。

5 个答案:

答案 0 :(得分:1)

很抱歉,如果我误解了您的问题,但似乎您可以使用OUTPUT声明中的INSERT条款解决问题 - 您可以在MSDN blog

中找到一条说明

答案 1 :(得分:0)

 INSERT INTO dbo.CS_RefQuestionChoice
       ( ChoiceDescription, 
         QuestionID, 
         RatingID, 
         SetID
       )
SELECT choice, 
       QuestionChoiceID, 
       ratingid,
       1 
  FROM CS_RefQuestions   
  WHERE QuestionChoiceID = SCOPE_IDENTITY() 

我假设CS_RefQuestions表中的标识列的名称为QuestionChoiceID

答案 2 :(得分:0)

DECLARE @ident int    
SET @ident = SCOPE_IDENTITY()

    INSERT INTO dbo.CS_RefQuestionChoice 
    (ChoiceDescription, 
             QuestionID, 
             RatingID, 
             SetID
           )
    SELECT choice, 
           @ident, 
           ratingid,
           1 
      FROM CS_RefQuestions 

答案 3 :(得分:0)

DECLARE @ident int    
SET @ident = IDENT_CURRENT(dbo.CS_RefQuestionChoice) AS Current_Identity
INSERT INTO dbo.CS_RefQuestionChoice(ChoiceDescription, QuestionID, RatingID, SetID)

SELECT @choice, @ident ,@ratingid,1 FROM CS_RefQuestions

答案 4 :(得分:0)

感谢所有的反馈,非常感谢。我知道我的问题很难理解,但是我可以在朋友的帮助下回答我的问题。这是我需要的代码:

USE [CCBBS_Survey_DB]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[SaveNewQuestionChoice]
@question VARCHAR(200),
@choice VARCHAR(100),
@qno INT,
@categid int,
@ratingid int
AS
BEGIN

IF NOT EXISTS(SELECT QuestionNo FROM CS_RefQuestions where QuestionNo = @qno)
    BEGIN
         INSERT INTO CS_RefQuestions(Question,QuestionNo,CategoryID, SetID)
         VALUES (@question, @qno, @categid, 1)
    END
ELSE
    BEGIN
        UPDATE  CS_RefQuestions 
        SET     Question = @question
                ,CategoryID = @categid
        WHERE QuestionNo = @qno
    END

 DECLARE @QUI INT

 SET @QUI = (SELECT TOP(1) QuestionID FROM CS_RefQuestions where QuestionNo = @qno)


 INSERT INTO dbo.CS_RefQuestionChoice(ChoiceDescription, QuestionID, RatingID, SetID)

 SELECT @choice, @QUI, @ratingid,1 FROM CS_RefQuestions RQ

 WHERE QuestionID = @QUI 

END