[英]SQL Server stored procedure. insert into table
The problem that I have is that 2 of my parameters that need to add into my table with a stored procedure are values that come from 2 other tables and I need to change these 2 values to the proper ones.我遇到的问题是,需要使用存储过程添加到我的表中的 2 个参数是来自其他 2 个表的值,我需要将这 2 个值更改为正确的值。
I have tried to search for the problem that I have but with no success.我试图寻找我遇到的问题,但没有成功。
There are 3 tables involved: Movie
, AgeRestriction
and Price
.涉及 3 个表: Movie
、 AgeRestriction
和Price
。
Table Movie
表Movie
Table AgeRestriction
:表AgeRestriction
:
Table Price
:表Price
:
The 2 values that i add is the value ( AgeRestriction, int
) from the AgeRestriction
table and ( Price, int
) from the Price
table.的2个值,我添加是值( AgeRestriction, int
从) AgeRestriction
表和( Price, int
从) Price
表。
This is how I need to insert the values I get into the table Movies
.这就是我需要将获得的值插入表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.");
}
}
}
So, I'm trying to create a stored procedure that can do all this but so far with no success so I'm asking you guys here..所以,我正在尝试创建一个可以完成所有这些操作的存储过程,但到目前为止还没有成功,所以我在这里问你们..
Okey, this is what ive tried:好的,这就是我尝试过的:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.