INSERT, SCOPE_IDENTITY, And Parameters...

Mar 14, 2007

I have a simple table Person (PersonID, PersonName, and PersonAge). PersonID is the primary key and it's also an identity field. Let me paste a sample code and I'll explain at the bottom what's happening. SqlConnection conn = new SqlConnection(@"Server=.SQLEXPRESS;Initial Catalog=Test;Trusted_Connection=True");
conn.Open();
try
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;

// delete all rows
cmd.CommandText = "DELETE FROM Person";
cmd.ExecuteNonQuery();

Response.Write("start... <br><br>");

// ad-hoc insert
cmd.CommandText = "SET IDENTITY_INSERT Person ON";
cmd.ExecuteNonQuery();
cmd.CommandText = "INSERT INTO Person(PersonID, PersonName, PersonAge) VALUES (5, 'John Smith', 20)";
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT SCOPE_IDENTITY()";
Response.Write("ID = ");
Response.Write(cmd.ExecuteScalar());
Response.Write("<br>");
cmd.CommandText = "SET IDENTITY_INSERT Person OFF";
cmd.ExecuteNonQuery();

// parameter insert
cmd.CommandText = "SET IDENTITY_INSERT Person ON";
cmd.ExecuteNonQuery();
cmd.CommandText = "INSERT INTO Person(PersonID, PersonName, PersonAge) VALUES (@PersonID, @PersonName, @PersonAge)";
p = new SqlParameter("@PersonID", 11);
p.Direction = ParameterDirection.Input;
cmd.Parameters.Add(p);
p = new SqlParameter("@PersonName", "Jon Doe2");
p.Direction = ParameterDirection.Input;
cmd.Parameters.Add(p);
p = new SqlParameter("@PersonAge", 21);
p.Direction = ParameterDirection.Input;
cmd.Parameters.Add(p);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "SELECT SCOPE_IDENTITY()";
Response.Write("ID = ");
Response.Write(cmd.ExecuteScalar());
Response.Write("<br>");
cmd.CommandText = "SET IDENTITY_INSERT Person OFF";
cmd.ExecuteNonQuery();

Response.Write("<br>end.");

}
finally
{
conn.Close();
}

I'm basically trying to insert rows in the table in two ways: one is ad-hoc (hardcoded sql statement) and another using parameters. Using the ad-hoc method everything is OK. Whenever I use the "parameter insert" method I can not get back the ID using SCOPE_IDENTITY (I always get back a DbNull value, the data gets into the table just fine). I'm rather new to using parameters, so it's gotta be something very easy that I'm missing...

Thank you.

View 4 Replies


ADVERTISEMENT

Retrieve ID Of Last Insert (Scope_Identity)

May 23, 2007

(Newbie) Hi, I am trying to create in a session variable, the ID of the last inserted record. My reading suggests I should use Scope_Identity. I'm having trouble with the syntax/code structure. Also, is it good programming practise to directly assign the session variable e.g. "Session[var]=SqlDataSource.Select()"? The error I'm getting from my code below is "No overload for method SELECT takes 0 arguments". Thanks.
Session["snCoDeptRowID"] = SqlDataSource1.Select();
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT Scope_Identity"
</asp:SqlDataSource>

View 4 Replies View Related

Updating A Column With Scope_Identity After An Insert Sometimes Does Not Work

Jan 21, 2008



Hello,

I have the following stored procedure that inserts records and updates the new record. The parameter @rpt_id has a value of -1 when entering the procedure. It needs to be updated with the new record if (identity) once the record is inserted, bu sometimes the update does not happen. The new records ends up with -1 in the rpt_id column.

I have included the stored procedure. I will appreciate any ideas?


ALTER PROCEDURE [dbo].[thhill_InsertReport]

(

@RPT_ID int,

@REPORT_DATE datetime,

@COMMIT_DATE datetime,

@JOB_NUMBER nvarchar(50),

@TECH_NAME nvarchar(75),

@CLIENT_NAME nvarchar(255),

@CLIENT_CONTACT nvarchar(75),

@CITY nvarchar(75),

@STATE nvarchar(75),

@COUNTRY nvarchar(75),

@SUPPLIER nvarchar(75),

@WORK_ORDER nvarchar(75),

@RIG_NAME nvarchar(75),

@WELL_NAME nvarchar(75),

@OCSG_NUMBER nvarchar(75),

@AFE_NUMBER nvarchar(75),

@MGMT varchar(6000),

@Complete varchar(3),

@newReportId int output,

@changeCommitDate bit = 1

)

AS

SET NOCOUNT ON;

if @changeCommitDate = 1

set @COMMIT_DATE = getdate()

INSERT INTO [reports] ([RPT_ID], [REPORT_DATE], [COMMIT_DATE], [JOB_NUMBER], [TECH_NAME], [CLIENT_NAME], [CLIENT_CONTACT], [CITY], [STATE], [COUNTRY], [SUPPLIER], [WORK_ORDER], [RIG_NAME], [WELL_NAME], [OCSG_NUMBER], [AFE_NUMBER], [MGMT], [isReportComplete])

VALUES (@RPT_ID, @REPORT_DATE, @COMMIT_DATE, @JOB_NUMBER, @TECH_NAME, @CLIENT_NAME, @CLIENT_CONTACT, @CITY, @STATE, @COUNTRY, @SUPPLIER, @WORK_ORDER, @RIG_NAME, @WELL_NAME, @OCSG_NUMBER, @AFE_NUMBER, @MGMT, @Complete );

declare @reference int, @tmpReportId int

set @tmpReportId = SCOPE_IDENTITY()

set @reference = @tmpReportId * -1


SET NOCOUNT Off;


Update [reports] set [RPT_ID] = @reference where id = @tmpReportId

select @newReportId = RPT_ID

FROM REPORTS

WHERE (ID = @tmpReportId)

View 3 Replies View Related

Sql Insert, Capture Scope_Identity Output To Session Variable?

May 24, 2007

What C# code would capture the Scope_Identity value (CoDeptRowID) output by the code below? Do I even need to capture it or is it already available as a C# variable CoDeptRowID ? I can't seem to get my hands on it!
SqlDataSource1.Insert();<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
InsertCommand="INSERT INTO [CompanyDepartment] ([User_Name], [FirstName], [LastName]) VALUES (@User_Name, @FirstName, @LastName);
SELECT @CoDeptRowID = SCOPE_IDENTITY()"
<insertparameters>
<asp:sessionparameter Name="User_Name" Type="String" SessionField ="LoginName"/>
<asp:controlparameter Name="FirstName" Type="String" ControlID="TextBox1" PropertyName ="text"/>
<asp:controlparameter Name="LastName" Type="String" ControlID ="TextBox2" PropertyName ="text"/>
<asp:Parameter Direction =Output Name ="CoDeptRowID" Type ="Int32" DefaultValue = "0" />
</insertparameters>
</asp:SqlDataSource>

View 5 Replies View Related

Insert With Parameters (SQL Server)

Jun 17, 2006

Hello, this is my code: SqlCommand cmd = new SqlCommand("INSERT INTO Users (Username,Password) " +
"VALUES ('@username','@password' ", new SqlConnection(my_ConnectionString));

cmd.Parameters.Add("@username", SqlDbType.NVarChar, 50).Value = txtUsername.Text;
cmd.Parameters.Add("@password", SqlDbType.NVarChar, 50).Value = txtPassword.Text

cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close(); But in the database, the row inserted is exactly this:"@username" "@password"I mean, the parameters are not inserted :SPlease, tell me the error in the code...Thank you so much,Carlos.

View 2 Replies View Related

Insert Data With Parameters And Sqldatasource

Apr 24, 2007

I have a sqldatasource in a wizard. When I click the finishbutton in the wizard I want to insert some values (from textboxes, dropdownlists in my wizard) into a mysql-database. For this I use parameters, I add some values in the design mode and some in codebehind. The parameters in codebehind are added perfectly but the other parameters in designmode (name, email) just inserts null. Why?  My datasource: <asp:SqlDataSource
ID="dsInsert"
InsertCommand="INSERT INTO tbltest (name, email, city) VALUES (?name, ?email, ?city)"
runat="server"
ConnectionString="<%$ ConnectionStrings:conn %>"
ProviderName="MySql.Data.MySqlClient">
<InsertParameters>
<asp:FormParameter Name="?name" ConvertEmptyStringToNull="true" Type="string" FormField="name" />
<asp:FormParameter Name="?email" ConvertEmptyStringToNull="true" Type="string" FormField="email" />
</InsertParameters>
</asp:SqlDataSource>   The codebehind:         protected void finishButtonClick(object sender, EventArgs e)        {            dsInsert.InsertParameters.Add("?city", TypeCode.Int32, city.SelectedValue);            dsInsert.Insert();        }

View 3 Replies View Related

Update/Insert Using XML Strings As Parameters

May 20, 2008

Hi All,

We got this little issue of passing around (updated and inserting) small dataSets (20-500 or so records) from fat clients to a remote server running .Net / SQL 2005.

Instead of trying to fudge the data and make updates in .Net, we just decided it would be a lot less nonsense if we just wrap up the dataSets in an XML string, have .Net just pass it thru as a parameter in a SP and let SQL parse it out using openXML. The data is small and server is low use, so I'm not worried about overhead, but I would like to know the best methods and DO's & Don'ts to parse the XML and make the updates/inserts....and maybe a few good examples. The few examples I've come across are kind of sketchy. Seems it's not a real popular method of handling updates.

Thanks in Advance,
Bill

View 5 Replies View Related

Insert From Parameters And Select Statement

May 30, 2006

Trying to insert into a history table. Some columns will come fromparameters sent to the store procedure. Other columns will be filledwith a separate select statement. I've tried storing the select returnin a cursor, tried setting the values for each field with a separateselect. Think I've just got the syntax wrong. Here's one of myattempts:use ESBAOffsetsgoif exists(select * from sysobjects where name='InsertOffsetHistory' andtype='P')drop procedure InsertOffsetHistorygocreate procedure dbo.InsertOffsetHistory@RECIDint,@LOB int,@PRODUCT int,@ITEM_DESC varchar(100),@AWARD_DATE datetime,@CONTRACT_VALUE float,@PROG_CONT_STATUS int,@CONTRACT_NUMBER varchar(25),@WA_OD varchar(9),@CURR_OFFSET_OBL float,@DIRECT_OBL float,@INDIRECT_OBL float,@APPROVED_DIRECT float,@APPROVED_INDIRECT float,@CREDITS_INPROC_DIRECT float,@CURR_INPROC_INDIRECT float,@OBLIGATION_REMARKS varchar(5000),@TRANSACTION_DATE datetime,@AUTH_USERvarchar(150),@AUTHUSER_LNAMEvarchar(150)asdeclare@idintinsert into ESBAOffsets..HISTORY(RECID,COID,SITEID,LOB,COUNTRY,PRODUCT,ITEM_DESC,AWARD_DATE,CONTRACT_VALUE,PROG_CONT_STATUS,CONTRACT_TYPE,FUNDING_TYPE,CONTRACT_NUMBER,WA_OD,PM,AGREEMENT_NUMBER,CURR_OFFSET_OBL,DIRECT_OBL,INDIRECT_OBL,APPROVED_DIRECT,APPROVED_INDIRECT,CREDITS_INPROC_DIRECT,CURR_INPROC_INDIRECT,PERF_PERIOD,REQ_COMP_DATE,PERF_MILESTONE,TYPE_PENALTY,PERF_GUARANTEE,PENALTY_RATE,STARTING_PENALTY,PENALTY_EXCEPTION,CORP_GUARANTEE,BANK,RISK,REMARKS,OBLIGATION_REMARKS,MILESTONE_REMARKS,NONSTANDARD_REMARKS,TRANSACTION_DATE,STATUS,AUTH_USER,PMLNAME,EXLD_PROJ,COMPLDATE,AUTHUSER_LNAME)values(@RECID,(Select COID from ESBAOffsets..Offsets_Master where RECID = @RECID),(Select SITEID from ESBAOffsets..Offsets_Master where RECID = @RECID),@LOB,(Select COUNTRY from ESBAOffsets..Offsets_Master where RECID =@RECID),@PRODUCT,@ITEM_DESC,@AWARD_DATE,@CONTRACT_VALUE,@PROG_CONT_STATUS,(Select CONTRACT_TYPE from ESBAOffsets..Offsets_Master where RECID =@RECID),(Select FUNDING_TYPE from ESBAOffsets..Offsets_Master where RECID =@RECID),@CONTRACT_NUMBER,@WA_OD,(Select PM from ESBAOffsets..Offsets_Master where RECID = @RECID),(Select AGREEMENT_NUMBER from ESBAOffsets..Offsets_Master where RECID= @RECID),@CURR_OFFSET_OBL,@DIRECT_OBL,@INDIRECT_OBL,@APPROVED_DIRECT,@APPROVED_INDIRECT,@CREDITS_INPROC_DIRECT,@CURR_INPROC_INDIRECT,(Select PERF_PERIOD from ESBAOffsets..Offsets_Master where RECID =@RECID),(Select REQ_COMP_DATE from ESBAOffsets..Offsets_Master where RECID =@RECID),(Select PERF_MILESTONE from ESBAOffsets..Offsets_Master where RECID =@RECID),(Select TYPE_PENALTY from ESBAOffsets..Offsets_Master where RECID =@RECID),(Select PERF_GUARANTEE from ESBAOffsets..Offsets_Master where RECID =@RECID),(Select PENALTY_RATE from ESBAOffsets..Offsets_Master where RECID =@RECID),(Select STARTING_PENALTY from ESBAOffsets..Offsets_Master where RECID= @RECID),(Select PENALTY_EXCEPTION from ESBAOffsets..Offsets_Master where RECID= @RECID),(Select CORP_GUARANTEE from ESBAOffsets..Offsets_Master where RECID =@RECID),(Select BANK from ESBAOffsets..Offsets_Master where RECID = @RECID),(Select RISK from ESBAOffsets..Offsets_Master where RECID = @RECID),(Select REMARKS from ESBAOffsets..Offsets_Master where RECID =@RECID),(Select OBLIGATION_REMARKS from ESBAOffsets..Offsets_Master whereRECID = @RECID),@MILESTONE_REMARKS,@NONSTANDARD_REMARKS,@TRANSACTION_DATE,(Select STATUS from ESBAOffsets..Offsets_Master where RECID = @RECID),@AUTH_USER,(Select PMLNAME from ESBAOffsets..Offsets_Master where RECID =@RECID),(Select EXLD_PROJ from ESBAOffsets..Offsets_Master where RECID =@RECID),(Select COMPLDATE from ESBAOffsets..Offsets_Master where RECID =@RECID),@AUTHUSER_LNAME)select@@identity idgogrant execute on InsertOffsetHistory to publicgo

View 1 Replies View Related

ADODB 2.8 - SQL Insert Statement - Using Parameters

Nov 20, 2007

Hi there,
I am trying to use the ADO technology within MS Access 2000. Basically I'd like to use parameters in a command object to insert a new record and get its newly inserted ID.
But instead of it it returns error:

Run-time error '-2147217900 (80040e14)
Must declare the scalar variable "@ii_file"

Isn't this varaible (and all the rest of variables) declared by setting a parameter ".Parameters.Append .CreateParameter("@ii_file", adVarChar, adParamInput, 255, Me.cbo_ii)
"?
I'd like to avoid using stored procedures in order to create the whole SQL statement from the client side.
Thanks!

Darek


Public Sub save_import()
Dim rs As ADODB.Recordset, cmd As ADODB.Command, rec_affected As Long

Set cmd = New ADODB.Command
With cmd
.ActiveConnection = ado_conn 'an existing connection
.CommandType = adCmdText
.CommandText = "insert into import_main (ii_file, id_file, oi_file, od_file, folder, import_desc, id_client,basis_of_study, id_is, project_leader, urisk_model_basis, as_at_date, extent_benchamark) " & _
"values (@ii_file, @id_file, @od_file, @od_file, @folder, @import_desc, @id_client, @basis_of_study, @id_is, @project_leader, @urisk_model_basis, @as_at_date, @extent_benchmark) " & _
"select @id_im = @@identity"
.Parameters.Append .CreateParameter("@id_im", adInteger, adParamOutput)

.Parameters.Append .CreateParameter("@ii_file", adVarChar, adParamInput, 255, Me.cbo_ii)
.Parameters.Append .CreateParameter("@id_file", adVarChar, adParamInput, 255, Me.cbo_id)
.Parameters.Append .CreateParameter("@oi_file", adVarChar, adParamInput, 255, Me.cbo_oi)
.Parameters.Append .CreateParameter("@od_file", adVarChar, adParamInput, 255, Me.cbo_od)
.Parameters.Append .CreateParameter("@folder", adVarChar, adParamInput, 1000, Me.txt_folder)
.Parameters.Append .CreateParameter("@import_desc", adVarChar, adParamInput, 255, Me.txt_import_desc)
.Parameters.Append .CreateParameter("@id_client", adBigInt, adParamInput, Me.cbo_client)
.Parameters.Append .CreateParameter("@basis_of_study", adVarChar, adParamInput, 255, Me.txt_basis_of_study)
.Parameters.Append .CreateParameter("@id_is", adSmallInt, adParamInput, Me.cbo_status)
.Parameters.Append .CreateParameter("@project_leader", adVarChar, adParamInput, 255, Me.txt_project_leader)
.Parameters.Append .CreateParameter("@urisk_model_basis", adVarChar, adParamInput, 1000, Me.txt_urisk_model)
.Parameters.Append .CreateParameter("@as_at_date", adDate, adParamInput, CDate(Me.txt_as_at_date))
.Parameters.Append .CreateParameter("@extent_benchmark", adVarChar, adParamInput, 1000, Me.txt_extent_benchmark)
.Parameters.Append .CreateParameter("@id_im", adInteger, adParamOutput)

.Execute rec_affected, , adExecuteNoRecords
If rec_affected > 0 Then
Me.cbo_import = .Parameters.Item("@id_im")
End If

End With


End Sub

View 3 Replies View Related

Insert Syntax When Passing Input Parameters

Dec 27, 2000

I'm trying something like this:

CREATE PROCEDURE Add_Junk @Dist char, @CheckNo int =null OUTPUT AS
Set NoCount On
BEGIN TRANSACTION
INSERT INTO Junk (Dist)
VALUES (@Dist)
COMMIT TRANSACTION
select @CheckNo=@@IDENTITY

If what I pass is "416" I only get the "4" in my database and nothing else.
I don't get an error message.
What is wrong with my syntax?

PS I'm using Microsoft SQL 7.0

View 2 Replies View Related

How To Run Insert Query For Required No.of Times With Different Parameters...?

Apr 22, 2008

Hi All,

I have two tables in my database.
I want to insert date and no.of hours worked on that day for a particular project.
So in a week if end user enters 7 dates and hrs for each day......
i have to insert those values into the table against one project only.
Can any one please help me out how to run insert query for 7 times (in a week) with different parameters

Thanks,
Praveen

View 5 Replies View Related

SqlDataSource With Different Number Of Columns And Insert Parameters And FormView

Dec 7, 2005

Dear All,
i have a SqlDataSource with a simple select command(e.g. "select a,b,c from foo"). The insert command is a stored procedure and takes less parameters than there are columns in select statement (e.g. "insertFoo(a char(10))").
When used in combination with form view, i get "Procedure or function insertFoo has too many arguments specified" error.
It seems that form view always posts all columns as parameter collection (breakpoint in formview_inserting event shows this) to insert command.
Am I doing something wrong or is this by design? Is the only solution to manualy tweak parameters in formview_inserting event?
TIA
   Jernej

View 2 Replies View Related

T-SQL (SS2K8) :: Parameters Passing Trough INSERT-SELECT Structures

Jul 4, 2014

I have got two user-defined functions: fn_Top and fn_Nested. The first one, fn_Top, is structured in this way:

CREATE FUNCTION [dbo].[fn_Top]
RETURNS @Results table (
MyField1 nvarchar(2000),
MyField2 nvarchar(2000)

[code]....

ENDI would like to perform a sort of dynamic parameter passing to the second function, fn_Nested, reading the values of the numeric field MyCounter in the table OtherTable.Fact is, x.MyCounter is not recognized as a valid value. Everything works fine, on the other hand, if I set in fn_Nested a static parameter, IE dbo.fn_Nested(17).

View 5 Replies View Related

SQL Server 2012 :: How To Insert One To Many Valued Parameters From A Stored Procedure Into A Table

Jan 14, 2015

I have a SP with Parameters as:

R_ID
P1
P2
P3
P4
P5

I need to insert into a table as below:

R_ID P1
R_ID P2
R_ID P3
R_ID P4
R_ID P5

How can I get this?

View 2 Replies View Related

Sql Insert Conversion Failed When Converting From A Character String To Uniqueidentifier. Error With Parameters

Dec 28, 2007

Hi,I'm new at asp .net and am having a problem. On a linkbutton click event, I want to insert into my db a row of data which includes two parameters. Param1 is the id of the logged in user, and Param2 is  <%#DataBinder.Eval(Container.DataItem, 'UserId')%> which is the username of a user given through a datalist.When I execute the query:   "insert into aspnet_friendship (userId, buddyId) values (@Param1, @Param2)"I get the error: Conversion failed when converting from a character string to uniqueidentifier.I am trying to insert these into my table aspnet_friendship into the columns userId and buddyId which are both uniqueidentifier fields. I tested the query using the same values  (@Param1, @Param1) and (@Param2, @Param2) and found out that the problem is with Param2 because when I use Param1 the insert works perfectly. The value passed by Param2 is supposed to be the id of a user which I get from the datalist which selects * from aspnet_Users, so that <%#DataBinder.Eval(Container.DataItem, 'UserId')%> should also be an Id like Param1 is. Since both params are in the form of .toString(), I don't understand why one works but the other doesn't.As you can see in the code below, both of these parameters are dimmed as strings, so I don't understand why Param2 doesn't work. Can anyone please help?  Protected Sub LinkButton1_Click(ByVal sender As Object, ByVal e As System.EventArgs)                Dim MyConnection As SqlConnection        MyConnection = New SqlConnection("Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|ASPNETDB.MDF;Integrated Security=True;User Instance=True")        Dim MyCommand2 As SqlCommand                Dim CurrentUser As String        CurrentUser = Membership.GetUser.ProviderUserKey.ToString()        Dim add As String        add = "<%#DataBinder.Eval(Container.DataItem, 'UserId')%>".ToString()        Session("username") = User.Identity.Name                Dim InsertCmd As String = "insert into aspnet_friendship (userId, buddyId) values (@Param1, @Param2)"                MyCommand2 = New SqlCommand(InsertCmd, MyConnection)                MyCommand2.Parameters.AddWithValue("@Param1", CurrentUser)        MyCommand2.Parameters.AddWithValue("@Param2", add)               MyCommand2.Connection.Open()        MyCommand2.ExecuteNonQuery()        MyCommand2.Connection.Close()    End Sub Thank you. 

View 3 Replies View Related

Using Scope_identity

Oct 20, 2007

Using scope_identity
I am using SQL2005 and I need to insert a record and return ID. I am using scope_identity() in the stored procedure to return the ID for the record just inserted.
Do you see any problem with this when it comes to multi-user and multi-threaded environment.
 

View 6 Replies View Related

Help On Scope_identity

Jan 3, 2008

Hi, i  need the DiagnosisID from the Diagnosis table to be copied and insert it into DiagnosisID from DiagnosisManagement. I was told to use scope_identity(), but i'm not sure how to implement it. Below is my code behind in vb.net. pls help. Dim cmd1 As New SqlCommand("insert into Diagnosis(TypeID, SeverityID, UniBilateral, PatientID, StaffID) values ('" & typevalue & "','" & severityvalue & "','" & unibivalue & "','" & Session("PatientID") & "','" & Session("StaffID") & "')", conn)        cmd1.ExecuteNonQuery()        Dim i As Integer        For i = 0 To hearingarray.Count - 1            Dim li As New ListItem            li = hearingarray(i)            Dim cmd As New SqlCommand("insert into DiagnosisManagement(ManagementID) values ('" & li.Value & "')", conn)        //i need the DIagnosisID from the Diagnosis table to be copied and insert it into DiagnosisID from DiagnosisManagement here            cmd.ExecuteNonQuery()        Next

View 1 Replies View Related

Using SCOPE_IDENTITY()

May 19, 2008

Hi All,
I'm trying to return the last id entered via the following code, and I'm only getting '0' back.
 1 using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString))
2 {
3 connection.Open();
4 using (SqlCommand command = new SqlCommand("REG_S_CustomerIDFromPhoneNumber", connection))
5 {
6 command.CommandType = CommandType.StoredProcedure;
7 command.Parameters.AddWithValue("@Mobile_Telephone", MobileNumber);
8
9 int test = Convert.ToInt32(command.ExecuteScalar());
10
11 Response.Write(test.ToString());
12
13
14 }
15 } My SP is as follows (I'm trying to use one that's already been written for me) 1 SET QUOTED_IDENTIFIER ON
2 GO
3 SET ANSI_NULLS ON
4 GO
5
6
7
8 ALTER PROCEDURE [dbo].[REG_I_CreateBlankCustomer]
9 @Mobile_Telephone varchar(255),
10 @CustomerID int OUTPUT
11
12 AS
13
14 INSERT INTO Customer (Mobile_Telephone)
15 VALUES (@Mobile_Telephone)
16
17 --SET @CustomerID = @@Identity
18 SELECT SCOPE_IDENTITY();
19
20
21 GO
22 SET QUOTED_IDENTIFIER OFF
23 GO
24 SET ANSI_NULLS ON
25 GO
26
27
28
 

 when I'm running this via Query Analyser, I get the ID returned correctly, however as mentioned when ran via that code above - I get a 0 outputted to me.  What am I doing wrong?
 
Thanks!

View 9 Replies View Related

Where To Put This SCOPE_IDENTITY

Jun 9, 2008

i have such a stored procedure.
 
but i dont know where to put that scope_identity to retrieve a value.
 SELECT SCOPE_IDENTITY() AS [@Car_id]
GO
ALTER procedure [dbo].[insertuser](
@Make nchar(10),
@Model nchar(10),
@SellerID varchar(50),
@MileAge nchar(10),
@Year_Model int,
@Price money,
@Date_added datetime,
@Thumb_ID varchar(50),
@Image_id varchar(50),
@Car_id int
)
AS
INSERT INTO
dbo.tbcar
VALUES(@Make,@Model,@SellerID,@MileAge,@Year_Model,@Price,@Date_added);
 
 
INSERT INTO
dbo.tbimages
values
(@Thumb_ID,@Image_id,@Car_id)

View 5 Replies View Related

SCOPE_IDENTITY() Help

Mar 30, 2005

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

View 2 Replies View Related

SCOPE_IDENTITY()

Mar 31, 2006

Hello altogether, my problem ist that I get following error message:
Create Stored ProcedureUnable to chances to the stored procedure.Error Details:'Scope_Identity' is not a recognized function name.
This is my Stored Procedure:
CREATE PROCEDURE sp_HyperSoftCustomer   @Name varchar(25),   @Adress varchar(250)as    insert into HyperSoftCustomer(Name, Adress, Date)    values (@Name, @Adress, GetDate())     Select SCOPE_IDENTITY() GO
I am using MSDE  -  MSSQLServer
I hope there is anybody who can help me?
Thanks, mexx

View 3 Replies View Related

Scope_identity From Vwd VB

Jun 3, 2006

I have seen plenty of messages about using scope_index by creating parameters using HTML but I would like to do it from my .aspx.vb page.
Does anybody know if this is possible? I have got as far as the code below and get stuck when trying to add a new parameter with direction of output.
Any help would be much appreciated, cheers,
Doug.
Dim NewProperty As SqlDataSource = New SqlDataSource
NewProperty.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectIt").ToString()
NewProperty.InsertCommand = "INSERT INTO Test (Name) VALUES (@Name); SET @NewID=SCOPE_IDENTITY()"
NewProperty.InsertParameters.Add(NewID, id)
NewProperty.Insert()

View 3 Replies View Related

Scope_identity()

Aug 23, 2004

I have four tables:
1- customer details
2- bank details
3- car details
4- contract details

All these tables are linked with the contract ID which is the primary key in table 4 and foriegn key in the rest. When a new customer inputs all the above data from the VB front, I want table 4 to give contract ID with a autonumber, which should be sent to the other tables, so that the contract in all tables are the same so that it is linked properly.....

I think I do this using scope-Identity? if so hoe do I do this? I'm using enterprise manager.....

Another question, customer table has a customer ID. What would be the primary key- customer ID, contract ID or both

THANKS

View 11 Replies View Related

I Need A Help About SCOPE_IDENTITY()

Aug 31, 2004

Hi All,

In SQL Server stored procedure
SCOPE_IDENTITY() will return the IDENTITY value inserted in Table, which was the last INSERT that occurred in the same scope.

can any one give me the syntax in Oracle ?

View 4 Replies View Related

SCOPE_IDENTITY()

Jan 10, 2008

Here's what I have (OrderID and CustID are PK's and autoincrement):

tblOrders__________tblCustomers
---------__________------------
OrderID____________CustID
CustID_____________Name

Just a simple application I created in ASP.NET and C# with those tables in an SQL database. The user enters their name, clicks Submit, and their information is put into Customers. After that, I want a new Order to be created with the CustID from the Customer just created.

I know I'm supposed to SCOPE_IDENTITY() to create it, but I'm not sure how to use it. I've been told to use a stored procedure, but I'm not sure how to do that either. Here's my code:

SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("INSERT INTO tblCustomers(Name)VALUES('"+TextBox1.Text+"');", conn);
//cmd2 with SCOPE_IDENTITY() inserting into tblOrders

conn.Open();
cmd.ExecuteNonQuery();
//cmd2.ExecuteNonQuery();
conn.Close();

View 18 Replies View Related

SCOPE_IDENTITY With ASP

Jul 23, 2005

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 theprimary key of the new row using SCOPE_IDENTITY. It then uses thatprimary key in the column of a second table (foreign key) to insertmany rows.What I'm seeing is an intermittent problem where the foreign key in thesecond table is not what it should be. I think the problem may be dueto the fact that the insert into the first table and the calling ofSCOPE_IDENTITY are done in 2 separate ASP statements with some ASP codein between.Is it possible that 2 users may be calling my ASP page at the same timeand causing a concurrency problem due to the INSERT and theSCOPE_IDENTITY being done in 2 different SQL statements? I read thatSCOPE_IDENTITY always returns the last identity value generated from"the current connection", so I thought that would mean that it wouldn'tget messed up by another ASP request. But now I'm thinking thatperhaps ASP uses connection pooling which could mean that 2 users couldbe sharing the same connection which would cause this concurrencyissue.Does anyone know if my theory of what's wrong is plausible?

View 5 Replies View Related

Scope_identity()

Jul 20, 2005

I have an ASP front end on SQL 2000 database. I have a form that submits toan insert query. The entry field is an "identity" and the primary key. Ihave used scope_identity() to display the entry# of the record just enteredon the confirmation page. Now I need to insert the entry into anothertable. This is my query:SET NOCOUNT ONINSERT wo_main(site_id, customer, po_number)VALUES ('::site_id::', '::customer::', '::po_number::')SELECT scope_identity() AS entryINSERT INTO wo_combo_body(entry) VALUES ('::entry::')SET nocount offThis query displays the entry number of the record just entered, but insertsa 0 in to entry field of the 2nd table. Any help would be great.Thanks,Darren

View 4 Replies View Related

SCOPE_IDENTITY()

Apr 6, 2006

is there an sql mobile equivalent of SCOPE_IDENTITY()?

View 4 Replies View Related

SCOPE_IDENTITY()

Sep 11, 2007



hi

what is difference between thos two's

SCOPE_IDENTITY()

and

@@IDENTITY


thanx

View 5 Replies View Related

Scope_Identity And SqlDataSource

Dec 28, 2006

have a detailsView control with an SqlDataSource whose insert statement looks like this:
InsertCommand="INSERT INTO [tblCompaniesNewSetRaw] ([NAME], [CITY], [ST], [ZIPCODE], [NAICS], [NAICSDESCRIPTION]) VALUES (@NAME, @CITY, @ST, @ZIPCODE, @NAICS, @NAICSDESCRIPTION); SELECT RETURN_VALUE = SCOPE_IDENTITY()"
also played with the same insert but used ...;Select SCOPE_IDENTITY()
my question is how do i get the last record inserted into tblCompaniesNewSetRaw after the insert is run.  ie I read that the Select Scope_identity() would return the value but how do i access the return value from within the code behind page, iusing VB.
some things i  tried in the detailsView_ItemInserted(...
Dim row As DetailsViewRow
For Each row In DetailsView3.Rows
x = row.Cells.Item(0).Text
Next
 in the VS debugger x is just "" and not the last record inserted in that table. 
probably way off base on this, clues appreciated, tc

View 3 Replies View Related

SCOPE_IDENTITY And SqlDataSource

Jun 29, 2007

Hi folks;I'm having trouble retrieving the SCOPE_IDENTITY() with an SqlDataSource, it returns a number that has nothing to do with the real identity.It was always returning 102 or 137 when the real identities were something in between 5 to 10
Here is my code: <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
DeleteCommand="DELETE FROM [POD] WHERE [PODID] = @PODID" InsertCommand="INSERT INTO [POD] ([CustomerID], [Airbill], [Shipper], [Consignee], [POD], [Date], [Time], [Pieces], [Weight], [Comments]) VALUES (@CustomerID, @Airbill, @Shipper, @Consignee, @POD, @Date, @Time, @Pieces, @Weight, @Comments); SELECT SCOPE_IDENTITY() AS @newID"
SelectCommand="SELECT * FROM [POD] ORDER BY [POD]" UpdateCommand="UPDATE [POD] SET [CustomerID] = @CustomerID, [Airbill] = @Airbill, [Shipper] = @Shipper, [Consignee] = @Consignee, [POD] = @POD, [Date] = @Date, [Time] = @Time, [Pieces] = @Pieces, [Weight] = @Weight, [Comments] = @Comments WHERE [PODID] = @PODID">
<DeleteParameters>
<asp:Parameter Name="PODID" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="CustomerID" Type="Int32" />
<asp:Parameter Name="Airbill" Type="String" />
<asp:Parameter Name="Shipper" Type="String" />
<asp:Parameter Name="Consignee" Type="String" />
<asp:Parameter Name="POD" Type="String" />
<asp:Parameter Name="Date" Type="DateTime" />
<asp:Parameter Name="Time" Type="DateTime" />
<asp:Parameter Name="Pieces" Type="Int32" />
<asp:Parameter Name="Weight" Type="Decimal" />
<asp:Parameter Name="Comments" Type="String" />
<asp:Parameter Name="PODID" Type="Int32" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="newID" Type="Int32" Direction="ReturnValue" />
<asp:Parameter Name="CustomerID" Type="Int32" />
<asp:Parameter Name="Airbill" Type="String" DefaultValue=" " />
<asp:Parameter Name="Shipper" Type="String" DefaultValue=" " />
<asp:Parameter Name="Consignee" Type="String" DefaultValue=" " />
<asp:Parameter Name="POD" Type="String" />
<asp:Parameter Name="Date" Type="DateTime" />
<asp:Parameter Name="Time" Type="DateTime" />
<asp:Parameter Name="Pieces" Type="Int32" DefaultValue="0" />
<asp:Parameter Name="Weight" Type="Decimal" DefaultValue="0" />
<asp:Parameter Name="Comments" Type="String" DefaultValue=" " />
</InsertParameters>
</asp:SqlDataSource> 
Protected Sub SqlDataSource1_Inserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) Handles SqlDataSource1.Inserted
' ** get the id and redirect to details page
Dim id As Integer = e.Command.Parameters("@newID").Value
Response.Redirect("pod_details.aspx?id=" & ID)
End Sub
 
Does anybody know what am i doing wrong in here?

View 2 Replies View Related

Scope_identity Question

Oct 12, 2007

I have a app that is inserting data into a SQL 2005 database and I would like to return the UniqueID of the inserted record.  I am using
Dim queryString As String = "INSERT INTO dbo.DATATABLE (FIELD) VALUES (@FIELD);SELECT Scope_Identity()"
Dim sID As String = comSQL.ExecuteScalar()
This isn't working - it says the value returned is DBNull...
 Any ideas on how to make this work?

View 4 Replies View Related

Is It Possible To Use SCOPE_IDENTITY() Twice In A Procedure

Oct 28, 2007

I have a stored procedure that does three INSERTS each needing to use the primary key from the previous. There are three INSERTS in the procedure.
Is this ok? my reason for asking is that it will get the first @IDPrimary but not the second @IDSecondary
For example;
INSERT (1)
Set @IDPrimary = SCOPE_IDENTITY()
INSERT(2)
Set @IDSecondary = SCOPE_IDENTITY()
INSERT(3)

View 6 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved