1

My procedure is:

CREATE PROCEDURE [dbo].[sp_SavePost]
    @PostTitle NVARCHAR(max),
    @PostDescription NVARCHAR(max),
    @PostDate DATETIME,
    @Author NVARCHAR(100),
    @Tag NVARCHAR(250), --it bring c#,asp.net,mvc
    @Category NVARCHAR(250)
AS
BEGIN
   INSERT INTO [dbo].[ForumPost](PostTitle, PostDescription, PostDate,
                                 Author, Tag, Category)
   VALUES(@PostTitle, @PostDescription, @PostDate,
          @Author, @Tag, @Category)
END

Table [dbo].[ForumPost] has postid which is auto increment. There is another tables called Tag. In a same procedure I want to insert a value into Tag table which has column postid and tag. But unable to insert a value in tag table. Means if postid=2 I want a result like this.

Table tag

postid | tag
------------
2      | c#
2      | asp.net
2      |  mvc

Thanks.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
4b0
  • 21,981
  • 30
  • 95
  • 142

1 Answers1

0

You need to get the latest inserted identity value and then use it in your second insert:

CREATE PROCEDURE [dbo].[sp_SavePost]
  .....
AS
BEGIN
   INSERT INTO [dbo].[ForumPost](PostTitle, PostDescription, PostDate,
                                 Author, Tag, Category)
   VALUES(@PostTitle, @PostDescription, @PostDate,
          @Author, @Tag, @Category)

   -- declare variable to hold newly inserted IDENTITY value
   DECLARE @NewPostID INT

   -- fetch the newly inserted IDENTITY value
   SELECT @NewPostID = SCOPE_IDENTITY()

   -- use that value in the next INSERT into the "Tag" table
   INSERT INTO dbo.Tag(PostId, ......)
   VALUES(@NewPostID, .......)
END

As a side-note: you should not use the sp_ prefix for your stored procedures. That's a prefix that Microsoft has reserved for its own use. There is a risk this will not work properly, or that it might cause slowdowns. I would avoid the sp_ prefix - use something like proc_ or no prefix that all...

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Thanks for suggestion.I get post id through `SCOPE_IDENTITY() ` but how can I split data `c#,asp.net,mvc` and insert into `Tag ` table. – 4b0 Apr 19 '12 at 05:15
  • @ShreeKhanal: there are **THOUSANDS** of posts on this - just Google or Bing for it! Or see [this other SO question](http://stackoverflow.com/questions/2647/split-string-in-sql) with several useful links.... – marc_s Apr 19 '12 at 05:17