我的存储过程是:
ALTER PROCEDURE [dbo].[ThemTram]
(
@Ten nvarchar(50),
@KhuVucID int,
@TenTinh nvarchar(50),
@TinhID int,
@TenTram nvarchar(50)
)
AS
set @KhuVucID = (select KhuVuc.KhuVucID from KhuVuc where KhuVuc.Ten=@ten)
set @TinhID =(select Tinh.TinhID from Tinh Where (Tinh.TenTinh=@TenTinh and Tinh.KhuVucID=@KhuVucID))
if not exists (select Tram.TenTram from Tram where (Tram.TenTram=@TenTram and Tram.TinhID = @TinhID))
Begin
insert into Tram(TenTram,TinhID) values (@TenTram,@TinhID)
end
和我的c#程序:
private void ThemTramBT_Click(object sender, EventArgs e)
{
string conn = "Data Source=USER-PC;Initial Catalog=NCKHmoi;Integrated Security=True";
SqlConnection connect = new SqlConnection(conn);
SqlCommand command = new SqlCommand();
command.Connection = connect;
connect.Open();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "ThemTram";
command.Parameters.Add("@Ten", SqlDbType.NVarChar, 50).Value = KhuVucComboBox.Text;
command.Parameters.Add("@TenTinh", SqlDbType.NVarChar, 50).Value = TinhComboBox.Text;
command.Parameters.Add("@TenTram", SqlDbType.NVarChar, 50).Value = ThemTramTB.Text;
command.Dispose();
connect.Close();
}
但有一个问题。在c#代码中。我无法向其插入新数据。 请帮帮我。
答案 0 :(得分:3)
您没有执行该命令。另外,您应该using
语句与SqlConnection
和(不太重要)SqlCommand
使用{/ 1>}:
private void ThemTramBT_Click(object sender, EventArgs e)
{
string conn = "Data Source=USER-PC;Initial Catalog=NCKHmoi;Integrated Security=True";
using (SqlConnection connect = new SqlConnection(conn))
{
using (SqlCommand command = new SqlCommand("ThemTram", conn))
{
connect.Open();
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@Ten", SqlDbType.NVarChar, 50).Value = KhuVucComboBox.Text;
command.Parameters.Add("@TenTinh", SqlDbType.NVarChar, 50).Value = TinhComboBox.Text;
command.Parameters.Add("@TenTram", SqlDbType.NVarChar, 50).Value = ThemTramTB.Text;
command.Parameters.AddWithValue("@KhuVucID", DBNull.Value); //need to pass even if not used
command.Parameters.AddWithValue("@TinhID", DBNull.Value); //need to pass even if not used
command.ExecuteNonQuery();
}
}
}
编辑:
根据您的评论,不清楚为什么您的程序员按照它的方式编码。我建议你改成如下:
ALTER PROCEDURE [dbo].[ThemTram]
(
@Ten nvarchar(50),
@TenTinh nvarchar(50),
@TenTram nvarchar(50)
)
AS
declare @KhuVucID int
declare @TinhID int
select @KhuVucID = KhuVuc.KhuVucID from KhuVuc where KhuVuc.Ten = @ten
select @TinhID = Tinh.TinhID from Tinh Where Tinh.TenTinh = @TenTinh and Tinh.KhuVucID = @KhuVucID
if not exists (select Tram.TenTram from Tram where Tram.TenTram = @TenTram and Tram.TinhID = @TinhID)
begin
insert into Tram(TenTram, TinhID) values (@TenTram, @TinhID)
end