如何将插入值的存储过程写入多个表

时间:2014-04-08 14:20:37

标签: sql sql-server stored-procedures

两个表

tblClass  - ClassID {PK} , ClassName
tblOperation - OperationID {PK} , OperationName , ClassId

从客户端来看,这些参数即将来临:

 @OperationName VARCHAR ,
 @ClassName VARCHAR  ,
 @UserID int

我想首先检查tblClass,如果类名不存在,那么类名应该添加到表中。

之后想检查tblOperation并检查类id和操作名称,如果不是必须插入的话。任何人都可以帮助我。

4 个答案:

答案 0 :(得分:0)

DECLARE @ClassCount AS TINYINT,
DECLARE @OperationCount AS TINYINT,
DECLARE @ClassID AS BIGINT

SELECT @ClassCount = COUNT(ClassName), @ClassID = ClassID  FROM tblClass WHERE ClassName = @ClassName 

IF(@ClassCount = 0)
BEGIN
INSERT INTO tblClass VALUES (@ClassName)
SELECT ClassID FROM tblClass WHERE ClassName = @ClassName
END

SELECT @OperationCount = COUNT(OperationName) FROM tblOperation WHERE OperationName = @OperationName

IF(@OperationCount = 0)
BEGIN
INSERT INTO tblOperation VALUES (@OperationName,@ClassID)
END

答案 1 :(得分:0)

我会假设您将检查该值是否存在,然后更新它,如果没有,则插入它。

这里有一些启动代码可以让你上路:)我还没有为你完成整个事情。

操纵以下内容以获得您想要的内容。

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE PROCEDURE NameOfStoredProc 
    -- Add the parameters for the stored procedure here
     @OperationName VARCHAR ,
     @ClassName VARCHAR  ,
     @UserID int
AS
IF EXISTS (SELECT ClassName FROM  tblClass WHERE ClassName = @ClassName)
BEGIN
    --UPDATE HERE
    --UPDATE TblClass SET ClassID = ###, ClassName = ### WHERE ?
    --UPDATE TblOperation SET OperationID  = ###, OperationName  = ###, ClassId - ### WHERE ?
END
ELSE
BEGIN
   -- INSERT HERE
   --INSERT INTO tblClass
   --INSERT INTO tblOperation
END

答案 2 :(得分:0)

CREATE PROCEDURE sp_InsertClassOperation
   @OperationName VARCHAR(100),
   @ClassName VARCHAR(100),
   @UserID INT

AS

IF NOT EXISTS (SELECT * FROM tblClass WHERE ClassName = @ClassName)
BEGIN
   INSERT INTO tblClass(ClassName) VALUES (@ClassName)
   DECLARE @ClassId INT = (SELECT ClassId FROM tblClass WHERE ClassName = @ClassName)

   IF NOT EXISTS (SELECT * FROM tblOperation WHERE OperationName = @OperationName AND ClassId = @ClassId)
   BEGIN
      INSERT INTO tblOperation(OperationName, ClassId) VALUES (@ClassId)
   END
END

答案 3 :(得分:0)

尝试这个概念:

  1. 在tblClass中运行更新查询

    更新tblclass set ... where classname ='something'

  2. 检查是否有任何行受影响,如果没有受影响的行运行插入查询

    如果@@ RowCount = 0
    插入到tblclass(...)值(....)

  3. 接下来运行tblOperation的更新查询

    更新tblOperation set classId = @@ Identity,...其中bla bla bla

  4. 检查是否有任何行受影响,如果没有受影响的行运行插入查询

    如果@@ RowCount = 0,请插入tblOperation(...,classId)值(...,@@ Identity)

  5. 访问In SQL, is there an alternative way to see if a record is already there before adding it?了解更多信息