Search code examples
asp.netsqlidentity-insert

I have a problem with my SQL statement


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

  Topics 
-----
 TopicsID 
Theme
 Topics 
Date 

Here is my statement:

  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)");

I get this:

Incorrect syntax near the keyword 'INTO'. Must declare the scalar variable "@TopicsID". Must declare the scalar variable "@TopicsID".


Solution

  • Try insertCommand.AppendLine

    SQL sees

    DECLARE @TopicsID intINSERT INTO Topics(Theme,Topics,Date) ...

    You need to separate the distinct statements