插入两个表和Identity Scope()

时间:2011-06-07 08:39:18

标签: asp.net sql insert

我正在建立一个论坛,我有两张桌子:

Threads
-------
ThreadID
UsersID
Date
ThreadTitle
ThreadParagraph
ThreadClosed


Topics
-----
TopicsID
Theme
Topics
Date

ThreadID通过主键连接到users表: Topics.TopicsID(PK)== Threads.TopicID(FK)

首先我插入Topics表,然后插入Threads表。我的目标是使用Identity_Scope()获取Topics.TopicID的ID,并将其传递给第二个插件,即Threads.TopicID

这是我所做的,但我不确定它是否正确:

StringBuilder insertCommand = new StringBuilder();
    insertCommand.Append("DECLARE @TopicsID int");
    insertCommand.Append("INSERT INTO Topics(Theme,Topics,Date)");
    insertCommand.Append("VALUES('@topic,@subTopic,GETDATE()')");
    insertCommand.Append("SET @TopicsID = SCOPE_IDENTITY()");

    insertCommand.Append("INSERT INTO Threads(UsersID,TopicsID,Date,ThreadTitle,ThreadParagraph,ThreadClosed)");
    insertCommand.Append("VALUES('@uniqueIdentifier,@TopicsID,GETDATE(),@questionTitle,@questionParagraph,0')");

我已经从用户按下或提供信息的控件中获得了所有的otehr参数,因此不必担心它们。我担心的是将相同的TopicID从Topic表传递给Thread表(列名:TopicID)。

1 个答案:

答案 0 :(得分:0)

Magnus& Damien_The_Unbeliever是对的 - 你几乎没有语法错误(或错别字)。正确的插入命令应该类似于

    insertCommand.Append(@"
          DECLARE @TopicSID int

          INSERT INTO Topics(Theme,Topics,Date)
          VALUES(@topic,@subTopic,GETDATE())

          SET @TopicSID = SCOPE_IDENTITY()

          INSERT INTO Threads(UsersID,TopicsID,Date,ThreadTitle,ThreadParagraph,ThreadClosed)
          VALUES(@uniqueIdentifier,@TopicSID ,GETDATE(),@questionTitle,@questionParagraph,0)
    ");