我正在尝试通过C#将数据插入到我的Sql- Server数据库中。我正在调用存储过程,然后希望将其添加。我不确定要进行哪些更改,但是最终我希望它在存储过程中完成。
我的存储过程现在:
CREATE PROCEDURE [dbo].[InsertTagProcdure] @TagID int, @Value nvarchar(200), @TagCount nvarchar(200) AS IF NOT EXISTS (SELECT NULL FROM Tag WHERE @TagID = @TagID) BEGIN INSERT INTO Tag (TagID,Value,TagCount) VALUES (@TagID,@Value,@TagCount) END
还有我的C#代码:
int TagID = int.Parse(txtTagID.Text); //This should fall away so auto increment. String Value = txtValue.Text; int TagCount = int.Parse(txtCount.Text); using (var conn = new SqlConnection(Properties.Settings.Default.DBConnectionString)) using (var cmd = conn.CreateCommand()) { conn.Open(); cmd.CommandText = "InsertTagProcdure"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@TagID", TagID); cmd.Parameters.AddWithValue("@Value", Value); cmd.Parameters.AddWithValue("@TagCount", TagCount); cmd.ExecuteNonQuery(); }
我使用的表创建://不能改变它,老板给我的。
CREATE TABLE [dbo].[Tag]( [TagID] [int] IDENTITY(1,1) NOT NULL, [Value] [varchar](200) NOT NULL, [TagCount] [varchar](200) NULL, CONSTRAINT [PK_Tag] PRIMARY KEY CLUSTERED ( [TagID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]
理想情况下,您只需通过更改表定义将TagID用作身份字段。如果您不能这样做,那么下一个最佳选择是:
CREATE PROCEDURE [dbo].[InsertTagProcdure] @Value nvarchar(200), @TagCount nvarchar(200) AS BEGIN BEGIN TRANSACTION DECLARE @TagID int; SELECT @TagID = coalesce((select max(TagID) + 1 from Tag), 1) COMMIT INSERT INTO Tag (TagID,Value,TagCount) VALUES (@TagID,@Value,@TagCount) END
事务确保您不会以唯一的TagID结尾,并且合并处理特殊情况,即表为空并给出初始值1。
编辑:
根据对原始问题的更改,该表已经具有一个标识列,因此您的存储过程应为:
CREATE PROCEDURE [dbo].[InsertTagProcdure] @Value nvarchar(200), @TagCount nvarchar(200) AS BEGIN INSERT INTO Tag (Value,TagCount) VALUES (@Value,@TagCount) END
并且您的C#代码应为
int TagID = int.Parse(txtTagID.Text); //这应该会消失,以便自动递增。字符串值= txtValue.Text; int TagCount = int.Parse(txtCount.Text);
using (var conn = new SqlConnection(Properties.Settings.Default.DBConnectionString)) using (var cmd = conn.CreateCommand()) { conn.Open(); cmd.CommandText = "InsertTagProcdure"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Value", Value); cmd.Parameters.AddWithValue("@TagCount", TagCount); cmd.ExecuteNonQuery(); }