Showing posts with label inserts. Show all posts
Showing posts with label inserts. Show all posts

Friday, March 30, 2012

Scripting "INSERT"s in an SQL database?

Hi there,

Getting ready for deployment and I would like to be able to run an install
script that will not just generate the schema, but fill in some of the
tables with default data. Is there a tool out there that will scan user
tables in an SQL database and generate the script required in order to
create a database with this default data?

Thanks

Robin"Robin Tucker" <idontwanttobespammedanymore@.reallyidont.com> wrote in
message news:c97t42$rmv$1$8300dec7@.news.demon.co.uk...
> Hi there,
> Getting ready for deployment and I would like to be able to run an install
> script that will not just generate the schema, but fill in some of the
> tables with default data. Is there a tool out there that will scan user
> tables in an SQL database and generate the script required in order to
> create a database with this default data?
> Thanks
>
> Robin

http://vyaskn.tripod.com/code.htm#inserts

If you have a lot of default data, it might be more efficient to have the
data in flat files and load it with bcp.exe or BULK INSERT.

Simon|||Hi

Another alternative would be to ship a default data and log file that is
already populated. For upgrades then a similar container but you would need
to use a tool such as those produced by www.red-gate.com sqlcompare or
www.innovartis.co.uk/Home.aspx dbghost or your home grown application.

John

"Robin Tucker" <idontwanttobespammedanymore@.reallyidont.com> wrote in
message news:c97t42$rmv$1$8300dec7@.news.demon.co.uk...
> Hi there,
> Getting ready for deployment and I would like to be able to run an install
> script that will not just generate the schema, but fill in some of the
> tables with default data. Is there a tool out there that will scan user
> tables in an SQL database and generate the script required in order to
> create a database with this default data?
> Thanks
>
> Robinsql

Friday, March 9, 2012

Script Component throws error

Hi,

I have three script component A,B, C. A reads certain data from a table. B inserts records into a .txt file when the recordtype = 1. C inserts records into same .txt file when the recordtype = 0. Now I receive a script comp error for C as follows.

[Error Desc]

************************************************************

The process cannot access the file 'D:\Documents and Settings\Administrator\Desktop\AuditLog.txt' because it is being used by another process.

************************************************************

at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)

at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)

at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)

at System.IO.StreamWriter.CreateFile(String path, Boolean append)

at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize)

at System.IO.StreamWriter..ctor(String path, Boolean append)

at ScriptComponent_6bda9d13fce34f90ac6315546c8d0d54.ScriptMain.PreExecute() in dts://Scripts/ScriptComponent_6bda9d13fce34f90ac6315546c8d0d54/ScriptMain:line 19

at Microsoft.SqlServer.Dts.Pipeline.ScriptComponentHost.PreExecute()

[/Error Desc]

Can anyone throw some light on it.

Thanks

If you have two script conponents trying to write to the same file at the same time, then this would seem a reasonable error. You will need to serialise the two write operations, as only one process can have a file open at a given time.|||

Hi,

Thanks for your reply. After completion of first script component only next gets executed.

In my example after B completes C starts. Also I have closed and disposed the stream writer object in the post execute of the script component B

How I can get rid of this. Also suggest any alternative solutions?

|||

Are all the script components in the same data-flow? If so then there is nothing to stop them trying to access the same file at the same time given that each component operates on one data buffer at a time. Each data buffer is a subset of all the data in the pipeline.

If you want to ensure that the script components are not accessing the same file concurrently put them in seperate, sequential, data flows. Or put them in 3 seperate files and then put them all together into a single file using UNION ALL component in a seperate data-flow.

-Jamie

Tuesday, February 21, 2012

SCOPE_IDENTITY()??

Hi All,
I have one doubt, if any one can help-me:
I have one SQL(db) that receive a lot of inserts, and I need get IDENTITY
value of current insert, but the machine have 4 processors.
If I use SCOPE_IDENTITY() I will get the corret value?
Thanks.Yes.
"ReTF" <re.tf@.newsgroup.nospam> wrote in message
news:OoNsEb$0FHA.3956@.TK2MSFTNGP09.phx.gbl...
> Hi All,
> I have one doubt, if any one can help-me:
> I have one SQL(db) that receive a lot of inserts, and I need get IDENTITY
> value of current insert, but the machine have 4 processors.
> If I use SCOPE_IDENTITY() I will get the corret value?
> Thanks.
>|||Might want to try IDENT_CURRENT as SCOPE_IDENTITY is scope specific.
HTH
Jerry
"ReTF" <re.tf@.newsgroup.nospam> wrote in message
news:OoNsEb$0FHA.3956@.TK2MSFTNGP09.phx.gbl...
> Hi All,
> I have one doubt, if any one can help-me:
> I have one SQL(db) that receive a lot of inserts, and I need get IDENTITY
> value of current insert, but the machine have 4 processors.
> If I use SCOPE_IDENTITY() I will get the corret value?
> Thanks.
>|||> Might want to try IDENT_CURRENT as SCOPE_IDENTITY is scope specific.
Actually, that is a lot more dangerous. Unless I read it wrong, the OP
wants the IDENTITY value generated by the current insert (SCOPE_IDENTITY),
not the most current IDENTITY value for the table (which may have changed
since the most recent insert in the current scope).
A

SCOPE_IDENTITY() Help

I was wondering if its possible to use this function if your using aSqlDataReader where I just run a stored procedure that just inserts arow?

Better might be a return value that you get at via a Return Code parameter using ExecuteNonQuery. No reason you could not do a SELECT SCOPE_IDENTITY() at the end of an INSERT SP and then get at it using ExecuteScalar() if you wish.

CREATE PROCEDURE spfoo
@.fooID int
AS
INSERT INTO fooTable(fooID) VALUES(@.fooID)
RETURN SCOPE_IDENTITY()

|||
Hi
Using SQLDataSource and SQL 2005 Stored Procedure I've been successful in creating multiple additional CreateUser fields saving them to "tbl_UserDetails" table.
I pass the UserId to the tbl_UserDetails as well. What I'm struggling with is retreiving the new tbl_UserDetails "Details_Id" - t-sql RETURN SCOPE_IDENTITY()).
I want to integrate it into the Profile data (see Profile creation below in CompleteButton_Click (71)).
I'm not sure if the problem retreiving the Details_Id is in the SQLDSInsert_Inserted (133) code used or if I'm not addressing the retreival in the "correct" stage of "the process". See below.
Thanks
1Imports Telerik.WebControls2Imports SITE.DAL.DBAccess3Imports System.Data4Imports System.Data.SqlClient56PartialClass Site_Pages_Registration7Inherits System.Web.UI.Page8Protected WithEvents Update_DateAs WebControls.HiddenField910Protected Sub Page_Load(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles Me.Load11If Session("Record") IsNotNothing Then12 CreateUserWizard1.MoveTo(CompleteWizardStep1)13End If1415 End Sub1617 Protected Sub CreateUserWizard1_CreatedUser(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles CreateUserWizard1.CreatedUser18Dim userAs MembershipUser = Membership.GetUser(CreateUserWizard1.UserName)1920If userIs Nothing Then21 Throw New ApplicationException("Can't find the user.")22 End If2324 Dim DetailsInsert As SqlDataSource = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("SQLDSInsert"), SqlDataSource)25 Dim UserId As Guid = DirectCast(user.ProviderUserKey, Guid)26 Session("NewUserId") = UserId27 Dim Details_FirstName As TextBox = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_FirstName"), TextBox)28 Dim Details_LastName As TextBox = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_LastName"), TextBox)29 Dim Details_MI As TextBox = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_MI"), TextBox)30 Dim Details_Title As TextBox = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_Title"), TextBox)31 Dim Details_Company As TextBox = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_Company"), TextBox)32 Dim Details_1Comm As Telerik.WebControls.RadMaskedTextBox = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_1Comm"), Telerik.WebControls.RadMaskedTextBox)33 Dim Details_1CommType As Telerik.WebControls.RadComboBox = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_1CommType"), Telerik.WebControls.RadComboBox)34 Dim Details_2Comm As Telerik.WebControls.RadMaskedTextBox = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_2Comm"), Telerik.WebControls.RadMaskedTextBox)35 Dim Details_2CommType As Telerik.WebControls.RadComboBox = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_2CommType"), Telerik.WebControls.RadComboBox)36 Dim Details_Address As TextBox = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_Address"), TextBox)37 Dim Details_City As TextBox = CType(CreateUserWizardStep0.ContentTemplateContainer.FindControl("Details_City"), TextBox)38 Dim Details_State As Telerik.WebControls.RadComboBox = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_State"), Telerik.WebControls.RadComboBox)39 Dim Details_Zip As Telerik.WebControls.RadMaskedTextBox = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_Zip"), Telerik.WebControls.RadMaskedTextBox)40 Dim Details_UserTypeId As Telerik.WebControls.RadComboBox = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_UserTypeId"), Telerik.WebControls.RadComboBox)41 Dim Details_ReceiveEmail As CheckBox = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_ReceiveEmail"), CheckBox)4243 DetailsInsert.Insert()4445 Dim UserType As Telerik.WebControls.RadComboBox = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_UserTypeId"), Telerik.WebControls.RadComboBox)46 Session("UserType") = UserType.SelectedValue.ToString47 End Sub4849 Protected Sub SQLDSInsert_Inserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceCommandEventArgs)50 Dim user As MembershipUser = Membership.GetUser(CreateUserWizard1.UserName)5152 e.Command.Parameters("@.UserId").Value = user.ProviderUserKey53 e.Command.Parameters("@.Details_FirstName").Value = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_FirstName"), TextBox).Text54 e.Command.Parameters("@.Details_LastName").Value = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_LastName"), TextBox).Text55 e.Command.Parameters("@.Details_MI").Value = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_MI"), TextBox).Text56 e.Command.Parameters("@.Details_Company").Value = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_Company"), TextBox).Text57 e.Command.Parameters("@.Details_Title").Value = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_Title"), TextBox).Text58 e.Command.Parameters("@.Details_1Comm").Value = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_1Comm"), Telerik.WebControls.RadMaskedTextBox).Text59 e.Command.Parameters("@.Details_1CommType").Value = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_1CommType"), Telerik.WebControls.RadComboBox).SelectedValue60 e.Command.Parameters("@.Details_2Comm").Value = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_2Comm"), Telerik.WebControls.RadMaskedTextBox).Text61 e.Command.Parameters("@.Details_2CommType").Value = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_2CommType"), Telerik.WebControls.RadComboBox).SelectedValue62 e.Command.Parameters("@.Details_Address").Value = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_Address"), TextBox).Text63 e.Command.Parameters("@.Details_City").Value = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_City"), TextBox).Text64 e.Command.Parameters("@.Details_State").Value = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_State"), Telerik.WebControls.RadComboBox).SelectedValue65 e.Command.Parameters("@.Details_Zip").Value = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_Zip"), Telerik.WebControls.RadMaskedTextBox).Text66 e.Command.Parameters("@.Details_UserTypeId").Value = Int32.Parse(CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_UserTypeId"), Telerik.WebControls.RadComboBox).SelectedValue)67 e.Command.Parameters("@.Details_ReceiveEmail").Value = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_ReceiveEmail"), CheckBox).Checked68 End Sub697071 Protected Sub CompleteButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)72 Dim user As MembershipUser = Membership.GetUser(CreateUserWizard1.UserName)7374 Dim pb As ProfileBase = ProfileBase.Create(user.UserName)75 pb.SetPropertyValue("FirstName", CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_FirstName"), TextBox).Text)76 pb.SetPropertyValue("LastName", CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_LastName"), TextBox).Text)77 pb.SetPropertyValue("UserName", CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("UserName"), TextBox).Text)78 pb.SetPropertyValue("Record", Session("Record"))79 pb.SetPropertyValue("Company", CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_Company"), TextBox).Text)80 pb.SetPropertyValue("Title", CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_Title"), TextBox).Text)81 pb.SetPropertyValue("Comm1", CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_1Comm"), Telerik.WebControls.RadMaskedTextBox).Text)82 pb.SetPropertyValue("Comm1Type", CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_1CommType"), Telerik.WebControls.RadComboBox).SelectedValue)83 pb.SetPropertyValue("Comm2", CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_2Comm"), Telerik.WebControls.RadMaskedTextBox).Text)84 pb.SetPropertyValue("Comm2Type", CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_2CommType"), Telerik.WebControls.RadComboBox).SelectedValue)85 pb.SetPropertyValue("Address", CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_Address"), TextBox).Text)86 pb.SetPropertyValue("City", CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_City"), TextBox).Text)87 pb.SetPropertyValue("State", CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_State"), Telerik.WebControls.RadComboBox).SelectedValue)88 pb.SetPropertyValue("Zip", CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_Zip"), Telerik.WebControls.RadMaskedTextBox).Text)8990 pb.Save()9192 Dim lblRegisterCompleteName As Label = CreateUserWizard1.CompleteStep.FindControl("lblRegisterCompleteName"), Label93 lblRegisterCompleteName.Text = Profile.FirstName & " " & Profile.LastName94 Dim Muser As MembershipUser = Membership.GetUser(CreateUserWizard1.UserName)95 If Muser Is Nothing Then96 Throw New ApplicationException("Can't find the user.")97End If98 Muser.IsApproved =False99 End Sub100101 Protected Sub btnTeamProfile_Click(ByVal senderAs Object,ByVal eAs System.EventArgs)102Dim userAs MembershipUser = Membership.GetUser(CreateUserWizard1.UserName)103104Dim pbAs ProfileBase = ProfileBase.Create(user.UserName)105 pb.SetPropertyValue("FirstName",CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_FirstName"), TextBox).Text)106 pb.SetPropertyValue("LastName",CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_LastName"), TextBox).Text)107 pb.SetPropertyValue("UserName",CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("UserName"), TextBox).Text)108 pb.SetPropertyValue("Record", Session("Record"))109 pb.SetPropertyValue("Company",CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_Company"), TextBox).Text)110 pb.SetPropertyValue("Title",CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_Title"), TextBox).Text)111 pb.SetPropertyValue("Comm1",CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_1Comm"), Telerik.WebControls.RadMaskedTextBox).Text)112 pb.SetPropertyValue("Comm1Type",CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_1CommType"), Telerik.WebControls.RadComboBox).SelectedValue)113 pb.SetPropertyValue("Comm2",CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_2Comm"), Telerik.WebControls.RadMaskedTextBox).Text)114 pb.SetPropertyValue("Comm2Type",CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_2CommType"), Telerik.WebControls.RadComboBox).SelectedValue)115 pb.SetPropertyValue("Address",CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_Address"), TextBox).Text)116 pb.SetPropertyValue("City",CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_City"), TextBox).Text)117 pb.SetPropertyValue("State",CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_State"), Telerik.WebControls.RadComboBox).SelectedValue)118 pb.SetPropertyValue("Zip",CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Details_Zip"), Telerik.WebControls.RadMaskedTextBox).Text)119120 pb.Save()121 Response.Redirect("Profile.aspx")122End Sub123124 Protected Sub CompleteWizardStep1_PreRender(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles CompleteWizardStep1.PreRender125Dim btnTeamProfileAs Button =CType(CompleteWizardStep1.ContentTemplateContainer.FindControl("btnTeamProfile"), Button)126If Session("UserType") ="2"Then127 btnTeamProfile.Visible =True128 Else129 btnTeamProfile.Visible =False130 End If131 End Sub132133 Protected Sub SQLDSInsert_Inserted(ByVal senderAs Object,ByVal eAs System.Web.UI.WebControls.SqlDataSourceCommandEventArgs)134Dim DetailsInsertAs SqlDataSource =CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("SQLDSInsert"), SqlDataSource)135Dim RecordAs Integer = DetailsInsert.InsertParameters.Add("@.Details_Id", System.Data.ParameterDirection.ReturnValue)136'Dim Record As Integer = e.Command.ExecuteScalar137 Session("Record") = Record.ToString138139 Response.Redirect("Registration.aspx")140End Sub141142143End Class144

SCOPE_IDENTITY with ASP

I am seeing a problem with an ASP application, where I have 2 tables.
In the first table, the ASP inserts just 1 row and retrieves the
primary key of the new row using SCOPE_IDENTITY. It then uses that
primary key in the column of a second table (foreign key) to insert
many rows.

What I'm seeing is an intermittent problem where the foreign key in the
second table is not what it should be. I think the problem may be due
to the fact that the insert into the first table and the calling of
SCOPE_IDENTITY are done in 2 separate ASP statements with some ASP code
in between.

Is it possible that 2 users may be calling my ASP page at the same time
and causing a concurrency problem due to the INSERT and the
SCOPE_IDENTITY being done in 2 different SQL statements? I read that
SCOPE_IDENTITY always returns the last identity value generated from
"the current connection", so I thought that would mean that it wouldn't
get messed up by another ASP request. But now I'm thinking that
perhaps ASP uses connection pooling which could mean that 2 users could
be sharing the same connection which would cause this concurrency
issue.

Does anyone know if my theory of what's wrong is plausible?hmm.. you got me here

Cowly the Game player

Please click on my links
http://spacefed.com
http://gc.gamestotal.org
http://uc.gamestotal.org
http://aw.gamestotal.org
http://www.gamestotal.org
http://3700ad.gamestotal.com
http://www.spacefederation.net
http://www.gamestotal.org/news/
http://ballmonster.gamestotal.com
http://www.spacefederation.net/manual/
http://gc.gamestotal.org/i.cfm?p=aboutgc
http://uc.gamestotal.org/i.cfm?p=aboutgc
http://www.gamestotal.org/corp/
http://www.gamestotal.org/strategygames/|||"Larry" <larry_grant_dc@.hotmail.com> wrote in message
news:1114610604.033965.138570@.o13g2000cwo.googlegr oups.com...
>I am seeing a problem with an ASP application, where I have 2 tables.
> In the first table, the ASP inserts just 1 row and retrieves the
> primary key of the new row using SCOPE_IDENTITY. It then uses that
> primary key in the column of a second table (foreign key) to insert
> many rows.
> What I'm seeing is an intermittent problem where the foreign key in the
> second table is not what it should be. I think the problem may be due
> to the fact that the insert into the first table and the calling of
> SCOPE_IDENTITY are done in 2 separate ASP statements with some ASP code
> in between.
> Is it possible that 2 users may be calling my ASP page at the same time
> and causing a concurrency problem due to the INSERT and the
> SCOPE_IDENTITY being done in 2 different SQL statements? I read that
> SCOPE_IDENTITY always returns the last identity value generated from
> "the current connection", so I thought that would mean that it wouldn't
> get messed up by another ASP request. But now I'm thinking that
> perhaps ASP uses connection pooling which could mean that 2 users could
> be sharing the same connection which would cause this concurrency
> issue.
> Does anyone know if my theory of what's wrong is plausible?

You don't mention if you're using stored procedures, but your description
seems to suggest you aren't. SCOPE_IDENTITY() returns the last value
inserted "within the current scope" - if you do your INSERTs in a stored
proc, then the proc itself is the scope, so there is no problem with
concurrency. But if you're executing each SQL statement directly, then there
could be a concurrency issue because all statements using the same
connection would share the same scope.

Apart from this issue, using stored procedures is generally a good idea, for
a number of security and performance reasons:

http://www.sommarskog.se/dynamic_sql.html#Why_SP

Simon|||I am not using stored procs.

I still have a question about your statement "there could be a
concurrency issue because all statements using the same connection
would share the same scope".

The connection is created within my ASP page. If several users call
the ASP page at the same time, is that considered the "same connection"
or different connections?|||"Larry" <larry_grant_dc@.hotmail.com> wrote in message
news:1114627612.035136.42880@.z14g2000cwz.googlegro ups.com...
>I am not using stored procs.
> I still have a question about your statement "there could be a
> concurrency issue because all statements using the same connection
> would share the same scope".
> The connection is created within my ASP page. If several users call
> the ASP page at the same time, is that considered the "same connection"
> or different connections?

If IIS opens only one connection to the server, then yes, that would all be
in the same scope. If each execution of the ASP page opens a new connection
to MSSQL (which seems unlikely to me, but I know almost nothing about ASP),
then they would be in different scopes. You can use sp_who2 to view the
current connections, and also see sysprocesses and @.@.SPID in Books Online.

If you're unsure about how ASP is managing connections, you'll probably get
better feedback in an ASP forum, although from a purely SQL perspective, I
suspect that using a stored proc should solve the issue anyway.

Simon|||Larry (larry_grant_dc@.hotmail.com) writes:
> I am seeing a problem with an ASP application, where I have 2 tables.
> In the first table, the ASP inserts just 1 row and retrieves the
> primary key of the new row using SCOPE_IDENTITY. It then uses that
> primary key in the column of a second table (foreign key) to insert
> many rows.
> What I'm seeing is an intermittent problem where the foreign key in the
> second table is not what it should be. I think the problem may be due
> to the fact that the insert into the first table and the calling of
> SCOPE_IDENTITY are done in 2 separate ASP statements with some ASP code
> in between.
> Is it possible that 2 users may be calling my ASP page at the same time
> and causing a concurrency problem due to the INSERT and the
> SCOPE_IDENTITY being done in 2 different SQL statements? I read that
> SCOPE_IDENTITY always returns the last identity value generated from
> "the current connection", so I thought that would mean that it wouldn't
> get messed up by another ASP request. But now I'm thinking that
> perhaps ASP uses connection pooling which could mean that 2 users could
> be sharing the same connection which would cause this concurrency
> issue.

I don't know ASP, but what is important is that you cannot use a
model where you connect for each query here, but you must use the
same connection for the two queries, so that you retain scope.

But it may be easier to send the SELECT satement as part of the
INSERT batch to save a round trip.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp

Scope_Identity with @Return_Value

I am currently writing an application that inserts data into a MS SQL Server 2000 DB. I am developing the application in Microsoft Visual Web Developer 2005 EE. So far everything has come together nicely. However, I have run into a situation that I can't seem to figure out.

I wrote a stored procedure to insert data into the DB from a Web Form. The insert works nicely; however, one of the requirements I have is that I would like the DB to return the last row inserted into to my table. I am using theScope_Identity() function at the end of my stored procedure to accomplish this task:

...Last few lines of Stored Procedure...

@.ANNEXCITYCOUNCILACTION,
@.CRA
)

RETURN SCOPE_IDENTITY()

GO

I have conducted several tests on the SP, and received the following output from the DB when it is run:

(1 row(s) affected)
(0 row(s) returned)
@.GID = <NULL>
@.RETURN_VALUE = 116
Finished running [dbo].[usp_InsertProject].

I would like to take the result of the @.RETURN_VALUE (116), and create a variable that I can use to embed into an e-mail. The code for the e-mail generation is working however, the value that comes through for the @.RETURN_VALUE is always 0. I have tried several different things to get this to work, but so far no luck.

Here is the application code I am using to create the e-mail:

Sub SendEmail()

Dim mySqlDataSource1 = SqlDataSource1.ConnectionString.ToString

Dim myConnection As New Data.SqlClient.SqlConnection(mySqlDataSource1)
Dim myCommand As New Data.SqlClient.SqlCommand("usp_InsertProject", myConnection)

myCommand.CommandType = Data.CommandType.StoredProcedure

Dim parameterGID As New Data.SqlClient.SqlParameter("@.RETURN_VALUE", Data.SqlDbType.Int)
parameterGID.Direction = Data.ParameterDirection.ReturnValue

myCommand.Parameters.Add(parameterGID)

Dim reader As Data.SqlClient.SqlDataReader = myCommand.ExecuteReader()

Dim GID As Integer = CInt(parameterGID.Value)
GID.ToString()

...E-mail code is below this, but is working, so not included ...

End Sub

I would like to insert the GID variable into the e-mail, but for some reason it won't work. The following error occurs when the InsertCommand is invoked:

ExecuteReader requires an open and available Connection. The connection's current state is closed.

You have two problems from what I can see. The first is indicated in the error. Run myConnection.Open() before you run a command against the database. Second is that you're running ExecuteReader(), but you don't seem to be using the data reader. If you're using it below, please ignore. If you aren't, you need to be running ExecuteNonQuery() instead.|||

Hi Chris,

Thanks for the help...I modifed the code, and added:

Email Sub changes:
myConnection.Open()
myCommand.ExecuteNonQuery()
myConnection.Close()

Stored Procedure changes:
@.CRA
)

SELECT
@.GID = @.@.Identity
GO

The results of the Stored Procedure are now:

(1 row(s) affected)
(0 row(s) returned)
@.GID = 127
@.RETURN_VALUE = 0
Finished running [dbo].[usp_InsertProject].

I now have an output parameter with the correct value I would like to set as a variable in my code.

However, the InsertCommand is being executed from a FormView, and is using a SqlDataSource to access the DB. When I put myConnection.Open() into the Sub it gives me the following error:

Error executing 'InsertCommand' in SqlDataSource 'SqlDataSource1'. Ensure the command accepts the following parameters: @.CREATEDBY, ...

The Sub is being run on the InsertButton_Click event. Is there a way to reference the open connection that the SqlDataSource object already has open? This way I can grab the @.GID value...

|||

If you want to use a sqldatasource for the insert, that's fine. Not knowing exactly how your database is set up, and what you can/can not change, it seems to me that what you want is:

Create a stored procedure that takes all your values, and returns a last inserted id. If you can not change the current stored procedure, create a new one that takes the same parameters, calls the original stored procedure then issues the T-SQL command RETURN SCOPE_IDENTITY(). If you do not already have a return value parameter set up for sqldatasource1's insert command, add one now (Or use the wizard to add all the parameters automatically, and it'll create @.RETURN_VALUE for you).

Inside the sqldatasource1_Inserted event (It must be done here), add code that looks like:

dim MyID as integer=e.command.parameters("@.RETURN_VALUE")

SendEmail(MyID)

Then remove all your myConnection/myCommand code, and change your SendEmail procedure to accept the id as a parameter.

|||

I got it to work by using the following code:

Protected Sub SqlDataSource1_Inserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) Handles SqlDataSource1.Inserted

Dim myID As Integer

myID = e.Command.Parameters("@.GID").Value

myID.ToString()

Dim Email As New Net.Mail.MailMessage()

E-mail code below this...

The key to getting it to work was putting it in the SqlDataSource1_Inserted event. This allowed me to get the output parameter.

Thanks for your help Motley...You pointed me in the right direction, and helped me out tremendously!

scope_identity Vs Parameters

Sorry for double posting but I screwed the last one up. The following code
successfully inserts a record in the Sections table, but the
scope_identity() returns DbNull. If I remove the parameter 'pSectionName'
and replace it with dummy value, it works fine. Alternatively, if I use
@.@.IDENTITY with or withour the parameter, that works fine too.
It seems there is a problem with using scope_identity() when parameters are
involved, but I do need to use parameters. Does anyone know why this would
happen and how to circumvent it ?
Dim sqlConnection As New SqlConnection(getConnectionString())
Dim sqlString As String
Dim result As Integer
Dim pSectionName As New SqlParameter("@.pSectionName",
SqlDbType.NVarChar)
pSectionName.Value = sectionRow.SectionName
sqlString = "INSERT INTO SECTIONS " & _
"VALUES (" & _
" '" & sectionRow.ArticleID.ToString & "'," & _
" @.pSectionName ," & _
" '" & sectionRow.SectionNumber.ToString & "'," & _
" '" & sectionRow.SectionFollowing.ToString & "'," & _
" '" & sectionRow.Attachments.ToString & "'," & _
" '" & sectionRow._Text & "'," & _
" ''," & _
" '" & sectionRow.pictureName & "'," & _
" '" & sectionRow.pictureType & "'," & _
" '" & sectionRow.pictureFilePath & "'," & _
" '" & sectionRow.SectionType & "');"
Dim sqlIDQuery As String
sqlIDQuery = "SELECT scope_identity();"
Dim sqlCommand As New SqlCommand(sqlString)
sqlCommand.Connection = sqlConnection
'Add Parameters
sqlCommand.Parameters.Add(pSectionName)
Dim SectionID As Integer
Try
sqlConnection.Open()
sqlCommand.ExecuteNonQuery() '***** THIS WORKS FINE AND
INSERTS RECORD.
sqlCommand.CommandText = sqlIDQuery
SectionID = CType(sqlCommand.ExecuteScalar, Integer) ' ****
FAILS HERE WITH AN EXCEPTION.
Catch ex As Exception
SectionID = 0
Finally
sqlConnection.Close()
End Try
Return SectionID
Best Regards
The Inimitable Mr NewbieHave you considered using a relational design, which will never have
IDENTITY in its tables? These exposed physical locators have nothign to
do with RDBMS or a valid logical model.
Have you considered using a stored procedure inside the database instead
of building a query on the fly at run time? Why do you think that a row
and record are anything alike?
A spec that tells us what you are trying to do, long with some DDL would
be very helpful. Do you program from things this vague and imcomplete?
Us, neither.
--CELKO--
Please post DDL in a human-readable format and not a machine-generated
one. This way people do not have to guess what the keys, constraints,
DRI, datatypes, etc. in your schema are. Sample data is also a good
idea, along with clear specifications.
*** Sent via Developersdex http://www.examnotes.net ***|||If you have nothing useful to say, just save it for someone who might care
that you try and make yourself feel good at the expense of others.
Especially those who are new like me.
Best Regards
The Inimitable Mr Newbie
"--CELKO--" <remove.jcelko212@.earthlink.net> wrote in message
news:OaEY7XgGGHA.2000@.TK2MSFTNGP15.phx.gbl...
> Have you considered using a relational design, which will never have
> IDENTITY in its tables? These exposed physical locators have nothign to
> do with RDBMS or a valid logical model.
> Have you considered using a stored procedure inside the database instead
> of building a query on the fly at run time? Why do you think that a row
> and record are anything alike?
> A spec that tells us what you are trying to do, long with some DDL would
> be very helpful. Do you program from things this vague and imcomplete?
> Us, neither.
> --CELKO--
> Please post DDL in a human-readable format and not a machine-generated
> one. This way people do not have to guess what the keys, constraints,
> DRI, datatypes, etc. in your schema are. Sample data is also a good
> idea, along with clear specifications.
>
> *** Sent via Developersdex http://www.examnotes.net ***|||I see you are reusing the same SqlCommand object but I don't see where you
are clearing the parameters collection from the first statement.
Consequently, the command will still contain the unneeded @.pSectionName
parameter when you execute SELECT SCOPE_IDENTITY(). You might try:
sqlCommand.Parameters.Clear()
sqlCommand.CommandText = sqlIDQuery
Also, consider parameterizing the entire INSERT statement or executing a
proc passing parameters. Parameterized values are more secure and avoid the
need to worry about things like embedded quotes in strings and date formats.
Hope this helps.
Dan Guzman
SQL Server MVP
"Mr Newbie" <here@.now.com> wrote in message
news:uqob9mfGGHA.2012@.TK2MSFTNGP14.phx.gbl...
> Sorry for double posting but I screwed the last one up. The following
> code successfully inserts a record in the Sections table, but the
> scope_identity() returns DbNull. If I remove the parameter
> 'pSectionName' and replace it with dummy value, it works fine.
> Alternatively, if I use @.@.IDENTITY with or withour the parameter, that
> works fine too.
> It seems there is a problem with using scope_identity() when parameters
> are involved, but I do need to use parameters. Does anyone know why this
> would happen and how to circumvent it ?
>
> Dim sqlConnection As New SqlConnection(getConnectionString())
> Dim sqlString As String
> Dim result As Integer
> Dim pSectionName As New SqlParameter("@.pSectionName",
> SqlDbType.NVarChar)
> pSectionName.Value = sectionRow.SectionName
> sqlString = "INSERT INTO SECTIONS " & _
> "VALUES (" & _
> " '" & sectionRow.ArticleID.ToString & "'," & _
> " @.pSectionName ," & _
> " '" & sectionRow.SectionNumber.ToString & "'," & _
> " '" & sectionRow.SectionFollowing.ToString & "'," & _
> " '" & sectionRow.Attachments.ToString & "'," & _
> " '" & sectionRow._Text & "'," & _
> " ''," & _
> " '" & sectionRow.pictureName & "'," & _
> " '" & sectionRow.pictureType & "'," & _
> " '" & sectionRow.pictureFilePath & "'," & _
> " '" & sectionRow.SectionType & "');"
> Dim sqlIDQuery As String
> sqlIDQuery = "SELECT scope_identity();"
> Dim sqlCommand As New SqlCommand(sqlString)
> sqlCommand.Connection = sqlConnection
> 'Add Parameters
> sqlCommand.Parameters.Add(pSectionName)
> Dim SectionID As Integer
> Try
> sqlConnection.Open()
> sqlCommand.ExecuteNonQuery() '***** THIS WORKS FINE AND
> INSERTS RECORD.
> sqlCommand.CommandText = sqlIDQuery
> SectionID = CType(sqlCommand.ExecuteScalar, Integer) ' ****
> FAILS HERE WITH AN EXCEPTION.
> Catch ex As Exception
> SectionID = 0
> Finally
> sqlConnection.Close()
> End Try
> Return SectionID
>
> --
> Best Regards
> The Inimitable Mr Newbie
>|||Thanks for your reply.
I tried clearing the Params, but that had no effect. so I created an
entirely new sqlCommandID object which used the same connection as the other
one for the scope_identity() but this had no effect.
I know I should parameterise the other parts of the sql query, but they dont
really need it because the contain no user input. Only the section title
carries this on creation.
Any other ideas. This is really bugging me.
Best Regards
The Inimitable Mr Newbie
"Dan Guzman" <guzmanda@.nospam-online.sbcglobal.net> wrote in message
news:OyzuingGGHA.2040@.TK2MSFTNGP14.phx.gbl...
>I see you are reusing the same SqlCommand object but I don't see where you
>are clearing the parameters collection from the first statement.
>Consequently, the command will still contain the unneeded @.pSectionName
>parameter when you execute SELECT SCOPE_IDENTITY(). You might try:
> sqlCommand.Parameters.Clear()
> sqlCommand.CommandText = sqlIDQuery
> Also, consider parameterizing the entire INSERT statement or executing a
> proc passing parameters. Parameterized values are more secure and avoid
> the need to worry about things like embedded quotes in strings and date
> formats.
>
> --
> Hope this helps.
> Dan Guzman
> SQL Server MVP
> "Mr Newbie" <here@.now.com> wrote in message
> news:uqob9mfGGHA.2012@.TK2MSFTNGP14.phx.gbl...
>|||> Have you considered using a relational design, which will never have
> IDENTITY in its tables? These exposed physical locators have nothign to
> do with RDBMS or a valid logical model.
Have you consider going one step further than the 'logical model' and create
an implementation or do you just deal with theory?
The IDENTITY property is a very useful way to create surrogate keys and gain
good performance and is a solution for the really big problem of when a
primary key value changes.

> Have you considered using a stored procedure inside the database instead
> of building a query on the fly at run time? Why do you think that a row
> and record are anything alike?
How do you think report builders work? Do you have a stored procedure with
1000 parameters and 1000 if else.
Actually, let me bring you up on this point, you posted a w or two ago
that you shouldn't use IF ELSE in the database.
Tony Rogerson
SQL Server MVP
http://sqlserverfaq.com - free video tutorials
"--CELKO--" <remove.jcelko212@.earthlink.net> wrote in message
news:OaEY7XgGGHA.2000@.TK2MSFTNGP15.phx.gbl...
> Have you considered using a relational design, which will never have
> IDENTITY in its tables? These exposed physical locators have nothign to
> do with RDBMS or a valid logical model.
> Have you considered using a stored procedure inside the database instead
> of building a query on the fly at run time? Why do you think that a row
> and record are anything alike?
> A spec that tells us what you are trying to do, long with some DDL would
> be very helpful. Do you program from things this vague and imcomplete?
> Us, neither.
> --CELKO--
> Please post DDL in a human-readable format and not a machine-generated
> one. This way people do not have to guess what the keys, constraints,
> DRI, datatypes, etc. in your schema are. Sample data is also a good
> idea, along with clear specifications.
>
> *** Sent via Developersdex http://www.examnotes.net ***|||You need to run it as a single statement, it would be better if you used a
stored procedure if possible.
Anyway, the problem lies in that SCOPE_IDENTITY() is only for the
connection, your connection will have been reset between calls.
You can concatenate sqlString and sqlIDQuery just put a semi column ; after
the first statement.
Tony Rogerson
SQL Server MVP
http://sqlserverfaq.com - free video tutorials
"Mr Newbie" <here@.now.com> wrote in message
news:uqob9mfGGHA.2012@.TK2MSFTNGP14.phx.gbl...
> Sorry for double posting but I screwed the last one up. The following
> code successfully inserts a record in the Sections table, but the
> scope_identity() returns DbNull. If I remove the parameter
> 'pSectionName' and replace it with dummy value, it works fine.
> Alternatively, if I use @.@.IDENTITY with or withour the parameter, that
> works fine too.
> It seems there is a problem with using scope_identity() when parameters
> are involved, but I do need to use parameters. Does anyone know why this
> would happen and how to circumvent it ?
>
> Dim sqlConnection As New SqlConnection(getConnectionString())
> Dim sqlString As String
> Dim result As Integer
> Dim pSectionName As New SqlParameter("@.pSectionName",
> SqlDbType.NVarChar)
> pSectionName.Value = sectionRow.SectionName
> sqlString = "INSERT INTO SECTIONS " & _
> "VALUES (" & _
> " '" & sectionRow.ArticleID.ToString & "'," & _
> " @.pSectionName ," & _
> " '" & sectionRow.SectionNumber.ToString & "'," & _
> " '" & sectionRow.SectionFollowing.ToString & "'," & _
> " '" & sectionRow.Attachments.ToString & "'," & _
> " '" & sectionRow._Text & "'," & _
> " ''," & _
> " '" & sectionRow.pictureName & "'," & _
> " '" & sectionRow.pictureType & "'," & _
> " '" & sectionRow.pictureFilePath & "'," & _
> " '" & sectionRow.SectionType & "');"
> Dim sqlIDQuery As String
> sqlIDQuery = "SELECT scope_identity();"
> Dim sqlCommand As New SqlCommand(sqlString)
> sqlCommand.Connection = sqlConnection
> 'Add Parameters
> sqlCommand.Parameters.Add(pSectionName)
> Dim SectionID As Integer
> Try
> sqlConnection.Open()
> sqlCommand.ExecuteNonQuery() '***** THIS WORKS FINE AND
> INSERTS RECORD.
> sqlCommand.CommandText = sqlIDQuery
> SectionID = CType(sqlCommand.ExecuteScalar, Integer) ' ****
> FAILS HERE WITH AN EXCEPTION.
> Catch ex As Exception
> SectionID = 0
> Finally
> sqlConnection.Close()
> End Try
> Return SectionID
>
> --
> Best Regards
> The Inimitable Mr Newbie
>|||--CELKO-- (remove.jcelko212@.earthlink.net) writes:
> Have you considered using a relational design, which will never have
> IDENTITY in its tables? These exposed physical locators have nothign to
> do with RDBMS or a valid logical model.
> Have you considered using a stored procedure inside the database instead
> of building a query on the fly at run time? Why do you think that a row
> and record are anything alike?
> A spec that tells us what you are trying to do, long with some DDL would
> be very helpful. Do you program from things this vague and imcomplete?
> Us, neither.
>
No, there is no spec needed. Instead of preteding like you are a bad
AI program let loose, learn how ADO .Net works and you will be answer
the question without any further spec.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||Mr Newbie (here@.now.com) writes:
> Sorry for double posting but I screwed the last one up. The following
> code successfully inserts a record in the Sections table, but the
> scope_identity() returns DbNull. If I remove the parameter
> 'pSectionName' and replace it with dummy value, it works fine.
> Alternatively, if I use @.@.IDENTITY with or withour the parameter, that
> works fine too.
> It seems there is a problem with using scope_identity() when parameters
> are involved, but I do need to use parameters. Does anyone know why this
> would happen and how to circumvent it ?
scope_idenity() returns the most recently generated identity value
in the current scope. Scope here is a stored procedure, or the top-
level scope. @.@.identity, on the other hand, returns the most recently
generated identity value for the connection, independent on scope.
When you don't use parameters, the INSERT command is submitted as-is,
and thus in the same scope as you later fetch scope_identity().
But when you use parameters, SqlClient submits the command through
sp_executesql. This is because SqlClient does not build the expanded
command string, but instead passes the parameters in an RPC call.
This is usually good for performance. The side effect is that the
INSERT statement no longer is in the top-level scope, and thus you
can get the identity value with scope_identity().
There are two possible ways to do:
o Use @.@.identity. This is fine as long as the table you are inserting
to does not have a trigger which in its turn insert into a table
with an identity column. In this case, @.@.identity will report the
value generated for that table. (It is to avoid this trap, that
scope_identity() was introduced.)
o As Tony suggested, add the SELECT on scope_identity() to the
batch with the INSERT statement.
The latter has the advantage of saving you a network roundtrip, which
is usally good for performance.
In fact, I would like to take you even a step further and do this:
sqlString = "INSERT INTO SECTIONS " & _
"(ArticleID, SectionName, SectionNumber, ... ) " & _
"VALUES (@.ArticleID, @.pSectionName, @.SectionNumber, ...) " & _
"SELECT @.id = scope_identity()"
1) Include the columns you are inserting into. If you leave out the column
list, and the table is later changed, you query will blow up.
2) Pass all values as parameters, don't embed values in the SQL String
(constants are OK). This protects you against SQL injection, and
other problems that could occur if the value includes an '. It also
saves you from hassle when using datetime values.
3) Make the value from scope_identity() an output parameter from
the batch. For this you need to specify the direction as InputOuput.
(SQL Server does not have any output-only parameters.)
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||>> If you have nothing useful to say, just save it for someone who might car
e that you try and make yourself feel good at the expense of others. Especia
lly those who are new like me. <<
So when I tell you think about stored procedures, it is a bad thing.
But when other people mention stored procedures as an answer, it is
good thing. Interesting.