如何使用函数编写存储过程?

时间:2012-07-30 04:28:49

标签: sql-server-2008 function stored-procedures

大家好我是新手,所以我在这里遇到麻烦

我有两张这样的表

错误

BugID|Title|ProjectName|CreatedBy

BugHistory

BughistoryID|BugID|Assignedto|ToStatus|FromStatus

我想为Bugs表编写一个插入存储过程,我将[Title]|[ProjectName][CreatedBy]插入bugs表,BugID表示身份和主键。

之后,我必须将BugID新标题和Tostatus插入BugHistory表格。这两个步骤应该在一个存储过程中完成。

我想要一个select语句,我必须在gridview中显示来自[AssignedTo]表的[Tostatus]BugHistory列的错误表。我怎么能在这两个程序中使用函数呢?

2 个答案:

答案 0 :(得分:0)

尝试在Bugs中创建一个触发器,以便在BugsHistory AFTER INSERT

中插入数据

答案 1 :(得分:0)

尝试这样的事情:

-- create stored procedure to insert a new bug, with parameters
CREATE PROCEDURE dbo.InsertBug 
    @Title VARCHAR(100),
    @ProjectName VARCHAR(100),
    @CreatedBy VARCHAR(100)
AS BEGIN

  -- variable to hold newly inserted "BugID"    
  DECLARE @NewBugID INT

  -- do the insert into the "Bugs" table      
  INSERT INTO dbo.Bugs(Title, ProjectName, CreatedBy)
  VALUES(@Title, @ProjectName, @CreatedBy)

  -- get the new BugID that's been assigned during INSERT      
  SELECT @NewBugID = SCOPE_IDENTITY()

  -- insert into the BugHistory table - since you didn't specify anything,
  -- I assumed the bug gets assigned to whoever created it by default,
  -- and I assumed "ToStatus" is a string column so I assigned "New" to it
  -- ADAPT as needed !
  INSERT INTO dbo.BUgHistory(BugID, AssignedTo, ToStatus)
  VALUES(@NewBugID, @CreatedBy, 'New')
END