0

我有两张桌子。

1-学生表和2-分数表

我想在学生表中插入值并在带有 SP 的分数表中插入多个值到 SQL Server 2008。

对于 EX:

ALTER proc [dbo].[InsertIntoScore]
(
@DateReg datetime,
@stdLastName nvarchar(50),
@stdFirstName nvarchar(50),
@Description nvarchar(500),

multi value as score table...
)
AS
DECLARE @Id AS INT
BEGIN TRY
BEGIN TRANSACTION
    INSERT INTO Student(DateReg,stdLastName,stdFirstName,[Description])
    VALUES (@DateReg,@stdLastName,@stdFirstName,@Description)
set @Id = SCOPE_IDENTITY() 

    insert multi value at Score table...    
COMMIT
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
    ROLLBACK
END CATCH

请帮我...

4

1 回答 1

0

您应该使用表值参数

为您将传入的表创建一个 Sql 类型

CREATE TYPE dbo.ScoreType AS TABLE ( ScoreID int, StudentID int, etc.... ) 

使用上面定义的类型将数据表从 C# 代码传递到存储过程

ALTER proc [dbo].[InsertIntoScore] 
( @DateReg datetime, @stdLastName nvarchar(50), @stdFirstName nvarchar(50), 
@Description nvarchar(500),  @tvpScore ScoreType) 
AS 
   .....
   INSERT INTO dbo.Score (ScoreID, StudentID, ....)     
   SELECT dt.ScoreID, @id, .... FROM @tvpScore AS dt; 

在c#中以这种方式传递数据表

SqlCommand insertCommand = new SqlCommand("InsertIntoScore", sqlConnection); 
SqlParameter p1 = insertCommand.Parameters.AddWithValue("@tvpScore", dtScore); 
p1.SqlDbType = SqlDbType.Structured; 
p1.TypeName = "dbo.ScoreType"; 
.....
insertCommand.ExecuteNonQuery(); 
于 2012-07-11T16:01:06.273 回答