473,403 Members | 2,354 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,403 software developers and data experts.

Simple SQL Server Insert Question

Hi Folks,
Just a quickie, I am inserting some records (individually) into a SQL
Server Table. I am wondering how can I detect primary key violations on
this data which I am inserting into the table.
My Insert code is as follows (VB.Net):

Public Function InsertNewUser(ByVal _ConnString As String, ByVal
UserAccess As UserAccess.Access) As Integer
Dim conn As New SqlConnection
Dim cmd As New SqlCommand
conn.ConnectionString = _ConnString
cmd.Connection = conn
cmd.CommandType = Data.CommandType.StoredProcedure
cmd.CommandText = "dbo.Access_Insert"
With cmd.Parameters
.AddWithValue("@Username", UserAccess.Username)
.AddWithValue("@RealName", UserAccess.Realname)
.AddWithValue("@accesslevel", 1)
.AddWithValue("@Email", UserAccess.Email)
.AddWithValue("@Webpage", UserAccess.Webpage)
.AddWithValue("@Sig", UserAccess.Sig)
.AddWithValue("Occupation", UserAccess.Occupation)
.AddWithValue("@Personal", UserAccess.Personal)
.AddWithValue("JoinDate", UserAccess.JoinDate)
.AddWithValue("@Password", UserAccess.Password)
End With
Try
conn.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Return -1
End Try
Return 0 ' success
End Function
As you can see this function returns 0 on success and -1 on failure. I
would like to be able to return some other integer value upon a primary
key conflict.

If anyone can help me out with this i'd be really gratful.
Kind Regards
Feb 1 '07 #1
7 1505
the exception has an Errors collection. you spin thru it looking for a
2627 message. you could also trap in the proc and pass back a flag.

also you have a connection leak in the sample code. you should have
finally clause that closes the conection.

-- bruce (sqlwork.com)

Materialised wrote:
Hi Folks,
Just a quickie, I am inserting some records (individually) into a SQL
Server Table. I am wondering how can I detect primary key violations on
this data which I am inserting into the table.
My Insert code is as follows (VB.Net):

Public Function InsertNewUser(ByVal _ConnString As String, ByVal
UserAccess As UserAccess.Access) As Integer
Dim conn As New SqlConnection
Dim cmd As New SqlCommand
conn.ConnectionString = _ConnString
cmd.Connection = conn
cmd.CommandType = Data.CommandType.StoredProcedure
cmd.CommandText = "dbo.Access_Insert"
With cmd.Parameters
.AddWithValue("@Username", UserAccess.Username)
.AddWithValue("@RealName", UserAccess.Realname)
.AddWithValue("@accesslevel", 1)
.AddWithValue("@Email", UserAccess.Email)
.AddWithValue("@Webpage", UserAccess.Webpage)
.AddWithValue("@Sig", UserAccess.Sig)
.AddWithValue("Occupation", UserAccess.Occupation)
.AddWithValue("@Personal", UserAccess.Personal)
.AddWithValue("JoinDate", UserAccess.JoinDate)
.AddWithValue("@Password", UserAccess.Password)
End With
Try
conn.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Return -1
End Try
Return 0 ' success
End Function
As you can see this function returns 0 on success and -1 on failure. I
would like to be able to return some other integer value upon a primary
key conflict.

If anyone can help me out with this i'd be really gratful.
Kind Regards
Feb 1 '07 #2
Yes you can, two ways:

1. Quick approach:
http://forums.asp.net/thread/1545938.aspx
2. Check if the primary key is violeted in stored proc i.e.
check if record with given index value (for instance username or email)
exists, add OUTPUT parameter to your stored procedure i.e. @exists int OUTPUT,
set it to nonzero value or constant code in case record with somecriteria
exists,
obtain its value after ExecuteNonQuery() and you're done

--
Milosz
"Materialised" wrote:
Hi Folks,
Just a quickie, I am inserting some records (individually) into a SQL
Server Table. I am wondering how can I detect primary key violations on
this data which I am inserting into the table.
My Insert code is as follows (VB.Net):

Public Function InsertNewUser(ByVal _ConnString As String, ByVal
UserAccess As UserAccess.Access) As Integer
Dim conn As New SqlConnection
Dim cmd As New SqlCommand
conn.ConnectionString = _ConnString
cmd.Connection = conn
cmd.CommandType = Data.CommandType.StoredProcedure
cmd.CommandText = "dbo.Access_Insert"
With cmd.Parameters
.AddWithValue("@Username", UserAccess.Username)
.AddWithValue("@RealName", UserAccess.Realname)
.AddWithValue("@accesslevel", 1)
.AddWithValue("@Email", UserAccess.Email)
.AddWithValue("@Webpage", UserAccess.Webpage)
.AddWithValue("@Sig", UserAccess.Sig)
.AddWithValue("Occupation", UserAccess.Occupation)
.AddWithValue("@Personal", UserAccess.Personal)
.AddWithValue("JoinDate", UserAccess.JoinDate)
.AddWithValue("@Password", UserAccess.Password)
End With
Try
conn.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Return -1
End Try
Return 0 ' success
End Function
As you can see this function returns 0 on success and -1 on failure. I
would like to be able to return some other integer value upon a primary
key conflict.

If anyone can help me out with this i'd be really gratful.
Kind Regards
Feb 1 '07 #3
Milosz Skalecki [MCAD] wrote:
Yes you can, two ways:

1. Quick approach:
http://forums.asp.net/thread/1545938.aspx
2. Check if the primary key is violeted in stored proc i.e.
check if record with given index value (for instance username or email)
exists, add OUTPUT parameter to your stored procedure i.e. @exists int OUTPUT,
set it to nonzero value or constant code in case record with somecriteria
exists,
obtain its value after ExecuteNonQuery() and you're done
Thanks for your reply Milosz,

I think the 2nd option is a lot more robust for the type of insert I am
working on. However I a a total newbie when it comes to doing this.
My stored procedure is as follows:

CREATE PROCEDURE [dbo].[Access_Insert]
@ID int,
@Username varchar(30),
@RealName varchar(100),
@AccessLevel int,
@Email varchar(50),
@Webpage varchar(50),
@Sig varchar(1000),
@Occupation varchar(200),
@Personal varchar(1000),
@JoinDate datetime,
@Password varchar(30)
AS
Insert into dbo.Access
(
Username,
RealName,
AccessLevel,
Email,
Webpage,
Sig,
Occupation,
Personal,
JoinDate,
Password
)
Values
(
@Username,
@RealName,
@AccessLevel,
@Email,
@Webpage,
@Sig,
@Occupation,
@Personal,
@JoinDate,
@Password
)

How would I implement something like what you suggested within this
procedure?
I understand that this is not a SQL Server programming group, but even
if you have a few small pointers I'm sure they will come in handy.

Kind Regards
Feb 1 '07 #4
Materialased.

Have a look in the ex code in your program what part you want to return.

return ex. (and have a look at the intelisense after you typed the dot)

Cor
"Materialised" <ma**********@privacy.netschreef in bericht
news:52*************@mid.individual.net...
Hi Folks,
Just a quickie, I am inserting some records (individually) into a SQL
Server Table. I am wondering how can I detect primary key violations on
this data which I am inserting into the table.
My Insert code is as follows (VB.Net):

Public Function InsertNewUser(ByVal _ConnString As String, ByVal
UserAccess As UserAccess.Access) As Integer
Dim conn As New SqlConnection
Dim cmd As New SqlCommand
conn.ConnectionString = _ConnString
cmd.Connection = conn
cmd.CommandType = Data.CommandType.StoredProcedure
cmd.CommandText = "dbo.Access_Insert"
With cmd.Parameters
.AddWithValue("@Username", UserAccess.Username)
.AddWithValue("@RealName", UserAccess.Realname)
.AddWithValue("@accesslevel", 1)
.AddWithValue("@Email", UserAccess.Email)
.AddWithValue("@Webpage", UserAccess.Webpage)
.AddWithValue("@Sig", UserAccess.Sig)
.AddWithValue("Occupation", UserAccess.Occupation)
.AddWithValue("@Personal", UserAccess.Personal)
.AddWithValue("JoinDate", UserAccess.JoinDate)
.AddWithValue("@Password", UserAccess.Password)
End With
Try
conn.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Return -1
End Try
Return 0 ' success
End Function
As you can see this function returns 0 on success and -1 on failure. I
would like to be able to return some other integer value upon a primary
key conflict.

If anyone can help me out with this i'd be really gratful.
Kind Regards

Feb 2 '07 #5
Materialased.
>
Have a look in the ex code in your program what part you want to return.

return ex. (and have a look at the intelisense after you typed the dot)

Cor

Thanks for that Cor,

Any ideas where I can find a list of error codes and their meanings? I
tried MSDN but cannot find such a list.

Regards
Feb 2 '07 #6
Hi there,

CREATE PROCEDURE [dbo].[Access_Insert]
@ID int OUTPUT,
@Username varchar(30),
@RealName varchar(100),
@AccessLevel int,
@Email varchar(50),
@Webpage varchar(50),
@Sig varchar(1000),
@Occupation varchar(200),
@Personal varchar(1000),
@JoinDate datetime,
@Password varchar(30),
@Exists BIT OUTPUT
AS

-- two ways of checking, i assume the only unique index is on [username] and
primary key [id]
-- first way
IF Exists(select [ID] from dbo.Access where [Username] = @Username)
BEGIN
@Exists = 1
RETURN;
END
ELSE @Exists = 0

-- another way
set @Exists = CAST( ISNULL((select 1 from dbo.Access where [Username] =
@Username), 0 ) as bit )
if @Exists <0 return;

Insert into dbo.Access
(
Username,
RealName,
AccessLevel,
Email,
Webpage,
Sig,
Occupation,
Personal,
JoinDate,
Password
)
Values
(
@Username,
@RealName,
@AccessLevel,
@Email,
@Webpage,
@Sig,
@Occupation,
@Personal,
@JoinDate,
@Password
)

-- one more thing, i changed @ID parameter to be OUTPUTed as
-- you didn't return any information about inserted id

SET @ID = Scope_Identity()
--
Milosz
"Materialised" wrote:
Milosz Skalecki [MCAD] wrote:
Yes you can, two ways:

1. Quick approach:
http://forums.asp.net/thread/1545938.aspx
2. Check if the primary key is violeted in stored proc i.e.
check if record with given index value (for instance username or email)
exists, add OUTPUT parameter to your stored procedure i.e. @exists int OUTPUT,
set it to nonzero value or constant code in case record with somecriteria
exists,
obtain its value after ExecuteNonQuery() and you're done
Thanks for your reply Milosz,

I think the 2nd option is a lot more robust for the type of insert I am
working on. However I a a total newbie when it comes to doing this.
My stored procedure is as follows:

CREATE PROCEDURE [dbo].[Access_Insert]
@ID int,
@Username varchar(30),
@RealName varchar(100),
@AccessLevel int,
@Email varchar(50),
@Webpage varchar(50),
@Sig varchar(1000),
@Occupation varchar(200),
@Personal varchar(1000),
@JoinDate datetime,
@Password varchar(30)
AS
Insert into dbo.Access
(
Username,
RealName,
AccessLevel,
Email,
Webpage,
Sig,
Occupation,
Personal,
JoinDate,
Password
)
Values
(
@Username,
@RealName,
@AccessLevel,
@Email,
@Webpage,
@Sig,
@Occupation,
@Personal,
@JoinDate,
@Password
)

How would I implement something like what you suggested within this
procedure?
I understand that this is not a SQL Server programming group, but even
if you have a few small pointers I'm sure they will come in handy.

Kind Regards
Feb 2 '07 #7
It was in the site link in my first post:
try
{
....
}
catch (SqlException ex)
{
switch (ex.Number)
{
case 4060: // Invalid Database
....
break;

case 18456: // Login Failed
....
break;

case 547: // ForeignKey Violation
....
break;

case 2627: // Unique Index/ Primary key Violation/ Constriant Violation
....
break;

case 2601: // Unique Index/Constriant Violation
....
break;

default:
....
break;
}
}
--
Milosz
"Materialised" wrote:
Materialased.

Have a look in the ex code in your program what part you want to return.

return ex. (and have a look at the intelisense after you typed the dot)

Cor

Thanks for that Cor,

Any ideas where I can find a list of error codes and their meanings? I
tried MSDN but cannot find such a list.

Regards
Feb 2 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: jet | last post by:
Hi, Maybe this is an easy task, but I'm having a really hard time figuring out how to do this. I'm a complete newbie to SQL Server. I have a database dump file from MySQL that's in .sql...
3
by: MBW | last post by:
The following code is for a simple server/client asplication that allows the user to toggle between serve and or client modes and send/recieve a message however i am getting an Attribute error on...
9
by: Pete | last post by:
Does anyone have a simple html vbscript or other type of snippet they can share that appends a record to a access database via ADO or DAO? I would like to allow users that don't have Microsoft...
20
by: TC | last post by:
I need an automated procedure to copy data from an Access table to a SQL Server table. Speed is important. What is the recommended technique? I can export the data from Access, copy it via FTP,...
4
by: dba_222 | last post by:
Dear Experts, Ok, I hate to ask such a seemingly dumb question, but I've already spent far too much time on this. More that I would care to admit. In Sql server, how do I simply change a...
14
by: dba_222 | last post by:
Dear experts, Again, sorry to bother you again with such a seemingly dumb question, but I'm having some really mysterious results here. ie. Create procedure the_test As
7
by: Materialised | last post by:
Hi Folks, Just a quickie, I am inserting some records (individually) into a SQL Server Table. I am wondering how can I detect primary key violations on this data which I am inserting into the...
7
by: Andres Rormoser | last post by:
I'm having a performance Issue with my Production SQL Server (2 x Xeon Dual-Core Woodcrest 1.6Ghz, 2GB RAM, IIS, SQL Server). In general the querys take much longer than the querys in my...
7
by: CSharper | last post by:
Yesterday I had a heated discussion with my colleagues on what is a data centric application and having business logic in sql. I have group of people who wants to include all the business logic in...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.