I am trying to insert Data into my Sql-Server database though C#. I’m Calling a stored procedure and then would like it to add. I’m not sure what changes to make, but ultimately i would like it done in the stored procedure.
My Stored procedure now:
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
And my C# Code:
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();
}
The Table Create i used: //Cant change this its what the boss gave me.
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]
Ideally you would just make TagID an identity field by changing the table definition. If you can’t do that, next best would be:
The transaction ensures that you don’t end up with unique TagIDs and the coalesce handles the special case where the table is empty and gives an initial value of 1.
EDIT:
Based on the change to your original question, the table already has an identity column so your stored procedure should be:
and your C# code should be
int TagID = int.Parse(txtTagID.Text); //This should fall away so auto increment.
String Value = txtValue.Text;
int TagCount = int.Parse(txtCount.Text);