SQL Server存储过程。插入表

时间:2015-08-28 15:23:23

标签: sql sql-server stored-procedures

我遇到的问题是需要使用存储过程添加到我的表中的2个参数是来自其他2个表的值,我需要将这2个值更改为正确的值。

我试图搜索我遇到的问题,但没有成功。

涉及3个表:MovieAgeRestrictionPrice

Movie

  • MovieID,int,PK
  • 电影,varchar(50)
  • 持续时间,时间(0)
  • AgeRestrictionID,int,FK - 与AgeRestriction表中的ID相关联
  • PriceID,int,FK - 与价格表中的ID相关联

AgeRestriction

  • AgeRestrictionID,int,PK
  • AgeRestriction,int

Price

  • PriceID,int,PK
  • Price,int

我添加的2个值是AgeRestriction, int表中的值{AgeRestriction)和Price, int表中的Price}。

这就是我需要将我得到的值插入表Movies

 public void InsertMovie(Movie movie)
 {
        using (SqlConnection conn = CreateConnection())
        {
            try
            {
                SqlCommand cmd = new SqlCommand("dbo.AddMovie", conn);
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.Add("@Movie", SqlDbType.NVarChar, 50).Value = movie._movie;
                cmd.Parameters.Add("@Duration", SqlDbType.Time, 0).Value = movie.Duration;
                cmd.Parameters.Add("@AgeRestriction", SqlDbType.Int, 50).Value = movie.AgeRestriction;
                cmd.Parameters.Add("@Price", SqlDbType.Decimal, 50).Value = movie.Price;

                conn.Open();
                cmd.ExecuteNonQuery();
            }
            catch
            {
                throw new ApplicationException("An error occured in the data access layer.");
            }
        }
    }

所以,我试图创建一个可以完成所有这些但是到目前为止没有成功的存储过程,所以我在这里问你们..

1 个答案:

答案 0 :(得分:0)

哦,这是我尝试过的:

ALTER PROCEDURE [dbo].[AddMovie]
@Movie varchar(50),
@Duration time(0),
@AgeRestrictionID int,
@PriceID int,
@AgeRestriction int,
@Price int
AS
BEGIN

SET NOCOUNT ON;

BEGIN TRANSACTION
        INSERT INTO Movie (Movie, Duration, AgeRestrictionID, PriceID)
        VALUES (@Movie, @Duration, @AgeRestrictionID, @PriceID)
        SELECT Movie, Duration, AgeRestriction, Price
        FROM Movie AS M
        INNER JOIN AgeRestriction as Ag ON M.AgeRestrictionID = Ag.AgeRestrictionID
        INNER JOIN Price as P ON M.PriceID = P.PriceID

COMMIT
END