我想从我的数据库调用存储过程,但它还需要一个属性列表作为类型,我将光标放在该类型上。但每次执行命令时,我都会收到异常,表示光标未打开。
我现在已经拥有
using (Connection = new SqlConnection(ConnectionString))
{
Connection.Open();
using (Command = new SqlCommand())
{
Command.Connection = Connection;
Command.CommandText = "CreateCharacter";
Command.CommandType = CommandType.StoredProcedure;
Command.Parameters.AddWithValue("@Skills", skills);
Command.Parameters.AddWithValue("@AccountId", accountId);
Command.Parameters.AddWithValue("@ClassId", masteryId);
Command.Parameters.AddWithValue("@RaceId", raceId);
Command.Parameters.AddWithValue("@Name", name);
try
{
return character = LoadCharacter(Convert.ToInt32(Command.ExecuteScalar()));
}
catch (Exception)
{
return null;
}
}
}
类型
CREATE TYPE dbo.AttributeList AS TABLE
(
AttributeId integer,
[Level] integer
);
GO
存储过程
CREATE PROCEDURE dbo.CreateCharacter (@Attributes AS dbo.AttributeList
READONLY, @AccountId integer, @ClassId integer, @RaceId integer, @Name
varchar(12))
AS
BEGIN
DECLARE AttributeCursor CURSOR FOR
SELECT
AttributeId,
[Level]
FROM @Attributes
INSERT INTO Character
VALUES (@ClassId, @RaceId, NULL, @Name, 1, 0, 0)
DECLARE @Id integer
DECLARE @AttributeId integer
DECLARE @AttributeLevel integer
SET @Id = IDENT_CURRENT('Character');
UPDATE Account
SET CharacterId = @Id
WHERE Id = @AccountId
WHILE (@@FETCH_STATUS = 0)
BEGIN
INSERT INTO Attribute_Character
VALUES (@AttributeId, @Id, @AttributeLevel)
FETCH NEXT FROM AttributeCursor INTO @AttributeId, @AttributeLevel
END
RETURN @Id;
END
答案 0 :(得分:0)
要发送Table参数,您只需在C#端构建一个DataTable:
var table = new DataTable();
table.Columns.Add("AttributeID", typeof(int));
table.Columns.Add("Level", typeof(int));
//Add data
table.Rows.Add(new []{1, 2});
//More code
Command.Parameters.AddWithValue("@Attributes", table);
我认为你在程序中不需要游标。只需插入数据:
INSERT INTO Attribute_Character(AttributeId, AttributeLevel)
SELECT AttributeId, AttributeLevel
FROM @Attributes