473,834 Members | 2,011 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem returning identity from SQL Server when string contains semicolon

Dan
I'm writing a record from an asp.net page to SQL Server. After the insert
I'm selecting @@identity to return the ID of the record that I just wrote.
It worked fine until I typed a semicolon into one of the string fields to be
inserted. The string fields are inside single quotes in the INSERT command.
With the semicolon in the string, the record is written correctly including
the semicolon, but the identity is not returned. Without a semicolon in the
string, the identity is returned correctly. The code is below, any
suggestions would be appreciated. The field with the semicolon is
ContractNumber. Thanks.

lsSQL = "INSERT INTO tblVPContracts (NonContracted, ContractNumber,
POReqNumber, ForInfoOnly, ImmediateAction Req, ModifiedBy) VALUES (" _
+ NonContracted.T oString + ", '" + tbContractNum.T ext + "', '" +
TextBox1.Text + "', " + ForInfoOnly.ToS tring + ", " +
ImmediateAction .ToString + ", " + UserID.ToString + " )"
Dim MyCommand As SqlCommand = New SqlCommand(lsSQ L, conn)
MyCommand.Execu teNonQuery()
Dim sSelect As String = "SELECT @@IDENTITY as NewID"
Dim DataSet As New DataSet
Dim adapter As New SqlDataAdapter
adapter.SelectC ommand = New SqlCommand(sSel ect, conn)
adapter.Fill(Da taSet, "Identity")
cookie.Values.A dd("VPContractI D",
DataSet.Tables( "Identity").Row s(0)(0))
Nov 20 '05 #1
3 4513
> I'm writing a record from an asp.net page to SQL Server. After the insert
I'm selecting @@identity to return the ID of the record that I just wrote.
It worked fine until I typed a semicolon into one of the string fields to be
inserted. The string fields are inside single quotes in the INSERT command.
With the semicolon in the string, the record is written correctly including
the semicolon, but the identity is not returned. Without a semicolon in the
string, the identity is returned correctly. The code is below, any
suggestions would be appreciated. The field with the semicolon is
ContractNumber. Thanks.

lsSQL = "INSERT INTO tblVPContracts (NonContracted, ContractNumber,
POReqNumber, ForInfoOnly, ImmediateAction Req, ModifiedBy) VALUES (" _
+ NonContracted.T oString + ", '" + tbContractNum.T ext + "', '" +
TextBox1.Text + "', " + ForInfoOnly.ToS tring + ", " +
ImmediateAction .ToString + ", " + UserID.ToString + " )"
Dim MyCommand As SqlCommand = New SqlCommand(lsSQ L, conn)
MyCommand.Execu teNonQuery()
Dim sSelect As String = "SELECT @@IDENTITY as NewID"
Dim DataSet As New DataSet
Dim adapter As New SqlDataAdapter
adapter.SelectC ommand = New SqlCommand(sSel ect, conn)
adapter.Fill(Da taSet, "Identity")
cookie.Values.A dd("VPContractI D",
DataSet.Tables( "Identity").Row s(0)(0))

If that Contract Number contained a single quote ('), then your sql
statement would fail. Look up "SQL Injection Attack".
So use Parameters to pass those values! See MSDN for details.
This might also solve your semicolon problem.

Second remark: instead of filling an entire dataset with that single
identity value, use ExecuteScalar (and cast the "object" result to an
integer). This will return just the first column in the first row of
the first resultset.

Hans Kesting
Nov 20 '05 #2
there are a lot issues with your code:

@@IDENTITY returns the last identity assigned in the sql batch. your select
@@IDENTITY is in its own batch, so it returns null. you need to switch to
one batch.

@@identity does not return the correct value if a trigger is used which also
creates an identity. you should use scope_ideneity( ) instead.

your code allows sql injection, you should switch to parameters.

string sql = @"set nocount on
INSERT INTO tblVPContracts (
NonContracted, ContractNumber, POReqNumber,
ForInfoOnly, ImmediateAction Req, ModifiedBy
)
VALUES (
@NonContracted, @ContractNum,@t extbox,
@ForInfoOnly,@I mmediateAction, @userid
)
select scope_identity as newid";

SqlCommand cmd = new SqlCommand(sql, conn)
cmd.Parameters. Add(@NonContrac ted,SqlDbType.I nt,0);
....
int newId = cmd.ExecuteScal er();
-- bruce (sqlwork.com)

"Dan" <da**********@p o.state.ct.us> wrote in message
news:ef******** ********@TK2MSF TNGP09.phx.gbl. ..
I'm writing a record from an asp.net page to SQL Server. After the insert
I'm selecting @@identity to return the ID of the record that I just wrote.
It worked fine until I typed a semicolon into one of the string fields to
be
inserted. The string fields are inside single quotes in the INSERT
command.
With the semicolon in the string, the record is written correctly
including
the semicolon, but the identity is not returned. Without a semicolon in
the
string, the identity is returned correctly. The code is below, any
suggestions would be appreciated. The field with the semicolon is
ContractNumber. Thanks.

lsSQL = "INSERT INTO tblVPContracts (NonContracted, ContractNumber,
POReqNumber, ForInfoOnly, ImmediateAction Req, ModifiedBy) VALUES (" _
+ NonContracted.T oString + ", '" + tbContractNum.T ext + "', '" +
TextBox1.Text + "', " + ForInfoOnly.ToS tring + ", " +
ImmediateAction .ToString + ", " + UserID.ToString + " )"
Dim MyCommand As SqlCommand = New SqlCommand(lsSQ L, conn)
MyCommand.Execu teNonQuery()
Dim sSelect As String = "SELECT @@IDENTITY as NewID"
Dim DataSet As New DataSet
Dim adapter As New SqlDataAdapter
adapter.SelectC ommand = New SqlCommand(sSel ect, conn)
adapter.Fill(Da taSet, "Identity")
cookie.Values.A dd("VPContractI D",
DataSet.Tables( "Identity").Row s(0)(0))

Nov 20 '05 #3
Dan
Both of these suggestions were a big help.
Thanks

"Hans Kesting" <ne***********@ spamgourmet.com > wrote in message
news:mn******** *************** @spamgourmet.co m...
I'm writing a record from an asp.net page to SQL Server. After the insert I'm selecting @@identity to return the ID of the record that I just wrote. It worked fine until I typed a semicolon into one of the string fields to be inserted. The string fields are inside single quotes in the INSERT command. With the semicolon in the string, the record is written correctly including the semicolon, but the identity is not returned. Without a semicolon in the string, the identity is returned correctly. The code is below, any
suggestions would be appreciated. The field with the semicolon is
ContractNumber. Thanks.

lsSQL = "INSERT INTO tblVPContracts (NonContracted, ContractNumber, POReqNumber, ForInfoOnly, ImmediateAction Req, ModifiedBy) VALUES (" _
+ NonContracted.T oString + ", '" + tbContractNum.T ext + "', '" +
TextBox1.Text + "', " + ForInfoOnly.ToS tring + ", " +
ImmediateAction .ToString + ", " + UserID.ToString + " )"
Dim MyCommand As SqlCommand = New SqlCommand(lsSQ L, conn)
MyCommand.Execu teNonQuery()
Dim sSelect As String = "SELECT @@IDENTITY as NewID"
Dim DataSet As New DataSet
Dim adapter As New SqlDataAdapter
adapter.SelectC ommand = New SqlCommand(sSel ect, conn)
adapter.Fill(Da taSet, "Identity")
cookie.Values.A dd("VPContractI D",
DataSet.Tables( "Identity").Row s(0)(0))

If that Contract Number contained a single quote ('), then your sql
statement would fail. Look up "SQL Injection Attack".
So use Parameters to pass those values! See MSDN for details.
This might also solve your semicolon problem.

Second remark: instead of filling an entire dataset with that single
identity value, use ExecuteScalar (and cast the "object" result to an
integer). This will return just the first column in the first row of
the first resultset.

Hans Kesting

Nov 20 '05 #4

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

Similar topics

8
9249
by: Bri | last post by:
Greetings, I'm having a very strange problem in an AC97 MDB with ODBC Linked tables to SQL Server 7. The table has an Identity field and a Timestamp field. The problem is that when a new record is entered, either from a form or from the table view of the table, when the record gets saved it immediately displays #DELETED# in all of the fields. However, if I close the form or table view and reopen the record has in fact been inserted. The...
3
2208
by: ferbar | last post by:
Hello all, This may sound pretty basic stuff.. but I'm working on a socket example whose client seems to work fine, but the server doesn't send to the client the expected result. The problem is that I want to trace what the server socket is doing, but I'm unable to see any of my fprintf or printf stuff. Please take a look to the example:
1
4761
by: Andrew | last post by:
Hey all, Working on revamping our Intranet here and making use of the LDPA, Active Directory, Directory Services, etc. that .Net provides. I am still fairly new on this subject, so the problem I have run into I am not sure how to fix, and really not sure what is causing it. Here's what is going on (test server - Windows 2003 Server): I have a page in a folder (under anonymous authentication in IIS6) that has a link on it that...
4
2192
by: Chris Gatto | last post by:
Hi, I'm having what should be a minor problem but has turned into a 2 day slug fest with ASP.Net. I am simply attempting to authenticate my asp.net application users against users in an AD group set up on our domain. It seems to me I am missing something very simple and obvious, but none of the MSDN articles I have read are indicating what this might be. My setup is ASP.Net running on a Windows 2003/IIS 6 server. IIS security...
4
1960
by: Jeff B | last post by:
I am having a very perplexing problem with setting the user's roles. I have tried to figure this out for 2 days now. When the user logs in to the site, I retrieve the roles from the database and create a semicolon delimited string listing the roles returned and store them in the forms authentication cookie. Then in the global.asax Application_AuthenticateRequest, I retrieve the FormsAuthenticationTicket from the forms authentication...
18
1804
by: jslowery | last post by:
I am not completely knowledgable about the status of lexical scoping in Python, but it was my understanding that this was added in a long time ago around python2.1-python2.2 I am using python2.4 and the following code throws a "status variable" not found in the inner-most function, even when I try to "global" it. def collect(fields, reducer): def rule(record): status = True
12
2269
by: Light | last post by:
Hi all, I posted this question in the sqlserver.newusers group but I am not getting any response there so I am going to try it on the fine folks here:). I inherited some legacy ASP codes in my office. The original code's backend is using the SQL Server 2000 and I am testing to use it on the Express edition. And I run into the following problem.
2
6667
myusernotyours
by: myusernotyours | last post by:
Hi All, Am working on a Java application in which I have to use the JNI to Interface with some native code for both windows and unix. Am using netbeans IDE with the C/C++ pack installed. Am also using Cygwin as my compiler (gcc), this is ostensibly because I hope this compiler will also compile the unix native libraries since I don't have a Linux installation. (I am working on a personal project from the office and can't get linux installed)....
9
14156
by: =?Utf-8?B?dHBhcmtzNjk=?= | last post by:
OK I have some Chinese text in sql server column that looks like this: 12大专题调研破解广东科学发展难题 This is unicode? Anyway, I put this data into a text area like this: articleArea.InnerHtml = article.Text . . .. and it works fine (shows chinese characters). But when I put this data into a asp:textbox control, it just shows up as is... (12大&# etc...) Can anyone tell me how to get the characters to appear...
0
9796
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
9643
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10789
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10214
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7755
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 presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6951
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5624
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5790
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3079
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.