2012-07-11 72 views
0

我有兩個表。用SP插入多值

1- student表& 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 

請幫我...

回答

0

您應該使用Table-Valued Parameters

創建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(); 
+0

我不能在@tvpScore ScoreType中使用ScoreType。我應該在哪裏寫這段代碼? CREATE TYPE dbo.ScoreType ... – 2012-07-11 17:23:10

+0

您可以在您計劃插入數據的SqlServer中創建它。使用Sql Server Management Studio。並且記住定義您計劃傳遞給存儲過程的表的所有字段。 – Steve 2012-07-11 19:44:02