Grab IDENTITY From Called Stored Procedure For Use In Second Stored Procedure In ASP.NET Page

Dec 28, 2005

I have a sub that passes values from my form to my stored procedure.  The stored procedure passes back an @@IDENTITY but I'm not sure how to grab that in my asp page and then pass that to my next called procedure from my aspx page.  Here's where I'm stuck:

    Public Sub InsertOrder()

        Conn.Open()

        cmd = New SqlCommand("Add_NewOrder", Conn)
        cmd.CommandType = CommandType.StoredProcedure

        ' pass customer info to stored proc
        cmd.Parameters.Add("@FirstName", txtFName.Text)
        cmd.Parameters.Add("@LastName", txtLName.Text)
        cmd.Parameters.Add("@AddressLine1", txtStreet.Text)
        cmd.Parameters.Add("@CityID", dropdown_city.SelectedValue)
        cmd.Parameters.Add("@Zip", intZip.Text)
        cmd.Parameters.Add("@EmailPrefix", txtEmailPre.Text)
        cmd.Parameters.Add("@EmailSuffix", txtEmailSuf.Text)
        cmd.Parameters.Add("@PhoneAreaCode", txtPhoneArea.Text)
        cmd.Parameters.Add("@PhonePrefix", txtPhonePre.Text)
        cmd.Parameters.Add("@PhoneSuffix", txtPhoneSuf.Text)

        ' pass order info to stored proc
        cmd.Parameters.Add("@NumberOfPeopleID", dropdown_people.SelectedValue)

        cmd.Parameters.Add("@BeanOptionID", dropdown_beans.SelectedValue)
        cmd.Parameters.Add("@TortillaOptionID", dropdown_tortilla.SelectedValue)

        'Session.Add("FirstName", txtFName.Text)

        cmd.ExecuteNonQuery()

        cmd = New SqlCommand("Add_EntreeItems", Conn)
        cmd.CommandType = CommandType.StoredProcedure
        cmd.Parameters.Add("@CateringOrderID", get identity from previous stored proc)   <-------------------------

        Dim li As ListItem
        Dim p As SqlParameter = cmd.Parameters.Add("@EntreeID", Data.SqlDbType.VarChar)
        For Each li In chbxl_entrees.Items
            If li.Selected Then
                p.Value = li.Value
                cmd.ExecuteNonQuery()
            End If
        Next

        Conn.Close()

I want to somehow grab the @CateringOrderID that was created as an end product of my first called stored procedure (Add_NewOrder)  and pass that to my second stored procedure (Add_EntreeItems)

View 9 Replies


ADVERTISEMENT

SQL Server 2014 :: Embed Parameter In Name Of Stored Procedure Called From Within Another Stored Procedure?

Jan 29, 2015

I have some code that I need to run every quarter. I have many that are similar to this one so I wanted to input two parameters rather than searching and replacing the values. I have another stored procedure that's executed from this one that I will also parameter-ize. The problem I'm having is in embedding a parameter in the name of the called procedure (exec statement at the end of the code). I tried it as I'm showing and it errored. I tried googling but I couldn't find anything related to this. Maybe I just don't have the right keywords. what is the syntax?

CREATE PROCEDURE [dbo].[runDMQ3_2014LDLComplete]
@QQ_YYYY char(7),
@YYYYQQ char(8)
AS
begin
SET NOCOUNT ON;
select [provider group],provider, NPI, [01-Total Patients with DM], [02-Total DM Patients with LDL],

[Code] ....

View 9 Replies View Related

How Do I Return The Identity From Stored Procedure To Asp.net Code Behind Page?

Jun 2, 2006

how do i return the identity from stored procedure to asp.net code behind page?
CREATE PROCEDURE [dbo].[myInsert] ( @Name varchar(35),   @LastIdentityNumber int output)AS insert into table1 (name) values (@name)
DECLARE @IdentityNumber intSET @IdentityNumber = SCOPE_IDENTITY()SELECT @IdentityNumber as LastIdentityNumber
code behind:
public void _Insert(
string _Name,
{
DbCommand dbCommand = db.GetStoredProcCommand("name_Insert");db.AddInParameter(dbCommand, "name", DbType.String, _userId);
db.AddParameter(dbCommand, "@IdentityNumber", DbType.Int32, ParameterDirection.Output, "", DataRowVersion.Current, null);
db.ExecuteNonQuery(dbCommand);
int a = (int)db.GetParameterValue(dbCommand,"@IdentityNumber");
whats wrong with to the above code?
 

View 2 Replies View Related

Is The Transaction Context Available Within A 'called' Stored Procedure For A Transaction That Was Started In Parent Stored Procedure?

Mar 31, 2008

I have  a stored procedure 'ChangeUser' in which there is a call to another stored procedure 'LogChange'. The transaction is started in 'ChangeUser'. and the last statement in the transaction is 'EXEC LogChange @p1, @p2'. My questions is if it would be correct to check in 'LogChange' the following about this transaction: 'IF @@trancount >0 BEGIN Rollback tran' END Else BEGIN Commit END.
 Any help on this would be appreciated.

View 1 Replies View Related

Why Is It Called Stored Procedure Instead Of Stored Sets?

Jul 23, 2005

Since RDMBS and its language SQL is set-based would it make more senseto call a given stored process "Stored Sets" instead of currenttheorically misleading Stored Procedure, as a measure to prodprogrammers to think along the line of sets instead of procedure?

View 4 Replies View Related

SqlDataSource And Stored Procedure Not Getting Called

Feb 23, 2007

Im using a SqlDataSource control. Ive got my "selectcommand" set to the procedure name, the "selectcommandtype" set to "storedprocedure"What am i doing wrong ?  Ive got a Sql 2005 trace window open and NO sql statements are coming through  "ds" runat="server" ConnectionString="&lt;%$ ConnectionStrings:myConnectionString %>" SelectCommand="my_proc_name" SelectCommandType="StoredProcedure">

"txtF1" Name="param1" Type="String" />
"txtF2" Name="param2" Type="String" />
"" FormField="txtF3" Name="param3" Type="String" />
"" FormField="txtF4" Name="param4" Type="String" />



  

View 2 Replies View Related

Update Stored Procedure Not Working When Called From C#

Jul 11, 2007

OK, I have been raking my brains with this and no solution yet. I simply want to update a field in a table given the record Id. When I try the SQL in standalone (no sp) it works and the field gets updated. When I do it by executing the stored procedure from a query window in the Express 2005 manager it works well too. When I use the stored procedure from C# then it does not work:
 1. ExecuteNonQuery() always returns -1 2. When retrieving the @RETURN_VALUE parameter I get -2, meaning that the SP did not find a matching record.
So, with #1 there is definitely something wrong as I would expect ExecuteNonQuery to return something meaningful and with #2 definitely strange as I am able to execute the same SQL code with those parameters from the manager and get the expected results.
Here is my code (some parts left out for brevity):1 int result = 0;
2 if (!String.IsNullOrEmpty(icaoCode))
3 {
4 icaoCode = icaoCode.Trim().ToUpper();
5 try
6 {
7 SqlCommand cmd = new SqlCommand(storedProcedureName);(StoredProcedure.ChangeAirportName);
8 cmd.Parameters.Add("@Icao", SqlDbType.Char, 4).Value = newName;
9 cmd.Parameters.Add("@AirportName", SqlDbType.NVarChar, 50).Value = (String.IsNullOrEmpty(newName) ? null : newName);
10 cmd.Parameters.Add("@RETURN_VALUE", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
11 cmd.Connection = mConnection; // connection has been opened already, not shown here
12 cmd.CommandType = CommandType.StoredProcedure;
13 int retval = cmd.ExecuteNonQuery(); // returns -1 somehow even when RETURN n is != -1
14 result = (int)cmd.Parameters["@RETURN_VALUE"].Value;
15
16 }
17 catch (Exception ex)
18 {
19 result = -1;
20 }
21 }

 And this is the stored procedure invoked by the code above:1 ALTER PROCEDURE [dbo].[ChangeAirfieldName]
2 -- Add the parameters for the stored procedure here
3 @Id bigint = null,-- Airport Id, OR
4 @Icao char(4) = null,-- ICAO code
5 @AirportName nvarchar(50)
6 AS
7 BEGIN
8 -- SET NOCOUNT ON added to prevent extra result sets from
9 -- interfering with SELECT statements.
10 SET NOCOUNT ON;
11
12 -- Parameter checking
13 IF @Id IS NULL AND @Icao IS NULL
14 BEGIN
15 RETURN -1;-- Did not specify which record to change
16 END
17 -- Get Id if not known given the ICAO code
18 IF @Id IS NULL
19 BEGIN
20 SET @Id = (SELECT [Id] FROM [dbo].[Airports] WHERE [Icao] = @Icao);
21 --PRINT @id
22 IF @Id IS NULL
23 BEGIN
24 RETURN -2;-- No airport found with that ICAO Id
25 END
26 END
27 -- Update record
28 UPDATE [dbo].[Airfields] SET [Name] = @AirportName WHERE [Id] = @Id;
29 RETURN @@ROWCOUNT
30 END

 As I said when I execute standalone UPDATE works fine, but when approaching it via C# it returns -2 (did not find Id).

View 2 Replies View Related

How To Check When A Stored Procedure Was Last Called/executed

Jul 23, 2005

HiOur SQL server has a lot of stored procedures and we want to get somecleaning up to be done. We want to delete the ones that have been notrun for like 2-3 months. How exactly will i find out which ones todelete. Enterprise manager only seesm to give the "Create Date"How exactly can I find the last called date ! I guess you could write aquery for that ! but how ???P.S I dont want to run a trace for 1 months and see what storedprocedures are not being used.

View 7 Replies View Related

How To Get The Output Parameter From An Internally Called Stored Procedure???

May 29, 2005

Hi all,i have a problem and couldnt find anything even close  to it. please help me, here is the description of what i m trying to accomplish:I have a trigger that is generating a column value and calling a stored procedure after the value is generated. And this stored procedure is setting this generated value as an output parameter. But my problem is:my asp.net page is only sending an insert parameter to the table with the trigger, trigger is running some code depending on the insert parameter and calling this other stored procedure internally. So basically i m not calling this last stored procedure that sets the output parameter within my web form. How can i get the output parameter in my webform? Everthing is working now, whenever an insert hits the table trigger runs and generates this value and called stored procedure sets it as an output parameter. I can get the output parameter with no problem in query analyzer, so the logic has no problem but i have no idea how this generated output parameter can be passed in my webform since its not initiated there.any help will greately be appreciated, i m sure asp.net and sql server 2000 is powerful and flexible enough to accomplish this but how??-shane

View 8 Replies View Related

Gettings Warnings Sent From A Stored Procedure Called With Jdbc

Dec 6, 2007

When running a stored procedure, how can i retrieve the warnings that are issued within the stored procedure?

the code used is below,

the jdbc is connecting fine, it is running the stored procedure, but when an error is raised in the stored procedure, it is not coming back into s.getwarnings()
warning raised in stored proc with





Code Block

RAISERROR ('Error', 16, 1)with nowait;

there are no results for the stored procedure, I am just wanting to get the warnings






Code Block

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

Connection con = DriverManager.getConnection("jdbc:sqlserver://localh...........);



CallableStatement s = con.prepareCall("{call procedure_name}");

s.execute();



//running in seprate thread

SQLWarning warn = s.getWarnings();
while (m.running) {
if(warn == null) {
warn = s.getWarnings();
}
safeOut(warn);
if(warn != null)
warn = warn.getNextWarning();
m.wait(100);

}the code is not complete, but should show what is happening

it is continually outputting null for the warning, though the strored proc is definately raising errors, which is proven by running it in a query window in sql server.

it is retreiving warning if the statement is a raiseerror instead of a call to the proc





Code Block

CallableStatement s = con.prepareCall("RAISERROR ('Error', 1, 1)with nowait;");

this thread is quite related, but doesnt offer a working solution
Getting messages sent while JDBC Driver calls stored procedure


any help much appreciated,

thankyou
Simon

View 1 Replies View Related

Debugging A CLR Stored Procedure That Is Being Called From An SSIS Package

Mar 3, 2008

I need help debugging a CLR stored procedure that is being called from an SSIS package. I can debug the procedure itself from within Visual Studio by using "Step into stored procedure" from Server Explorer, but really need to debug it as it is being called from SSIS.

View 4 Replies View Related

Dynamic Security Stored Procedure Repeatedly Called

Jan 26, 2007

I have implemented an SSAS stored procedure for dynamic security and I call this stored procedure to obtain the allowed set filter. To my supprise, the stored procedure is being called repeatedly many times (more than 10) upon establishing the user session. Why is this happening?

View 20 Replies View Related

DB Engine :: Can Find A Record Of Stored Procedure Being Called?

Jul 15, 2015

I seem to be able to see where a procedure is being recompiled, but not the actual statement that was executing the procedure.

Note, with 2008 there is a DMV called dm_exec_procedure_statsĀ , which is not present in 2005

USE YourDb;

SELECT qt.[text] AS [SP Name],
qs.last_execution_time,
qs.execution_count AS [Execution Count]
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt
WHERE qt.dbid = DB_ID()
AND objectid = OBJECT_ID('YourProc')

The above shows results that include the CREATE PROCEDURE statements for the procedure in question, but this only indicates that the procedure was being recompiled, not necessarily that it was being executed?

View 3 Replies View Related

Debugging A CLR Stored Procedure That Is Being Called From An SSIS Package

Mar 3, 2008


I need help debugging a CLR stored procedure that is being called from an SSIS package. I can debug the procedure itself from within Visual Studio by using "Step into stored procedure" from Server Explorer, but really need to debug it as it is being called from SSIS.

View 3 Replies View Related

Can A Stored Procedure Called From An Inline Table-Valued Function

Oct 5, 2006

Hi,

I'm trying to call a Stored Procedure from a Inline Table-Valued Function. Is it possible? If so can someone please tell me how? And also I would like to call this function from a view. Can it be possible? Any help is highly appreciated. Thanks

View 4 Replies View Related

Identifying Results Sets When Stored Procedure Called Multiple Times

Oct 18, 2005

I have a report based on our product names that consists of two parts.Both insert data into a temporary table.1. A single grouped set of results based on all products2. Multiple tables based on individual product names.I am getting data by calling the same stored procedure multipletimes... for the single set of data I use "product like '%'"To get the data for individual products, I am using a cursor to parsethe product list.It's working great except that I have no idea how to identify theresults short of including a column with the product name. While thatis fine, I'm wondering if there is something that is like a header ortitle that I could insert prior to generating the data that would looka little tighter.Thanks in advance-DanielleJoin Bytes!

View 3 Replies View Related

Calling A Stored Procedure Inside Another Stored Procedure (or Nested Stored Procedures)

Nov 1, 2007

Hi all - I'm trying to optimized my stored procedures to be a bit easier to maintain, and am sure this is possible, not am very unclear on the syntax to doing this correctly.  For example, I have a simple stored procedure that takes a string as a parameter, and returns its resolved index that corresponds to a record in my database. ie
exec dbo.DeriveStatusID 'Created'
returns an int value as 1
(performed by "SELECT statusID FROM statusList WHERE statusName= 'Created') 
but I also have a second stored procedure that needs to make reference to this procedure first, in order to resolve an id - ie:
exec dbo.AddProduct_Insert 'widget1'
which currently performs:SET @statusID = (SELECT statusID FROM statusList WHERE statusName='Created')INSERT INTO Products (productname, statusID) VALUES (''widget1', @statusID)
I want to simply the insert to perform (in one sproc):
SET @statusID = EXEC deriveStatusID ('Created')INSERT INTO Products (productname, statusID) VALUES (''widget1', @statusID)
This works fine if I call this stored procedure in code first, then pass it to the second stored procedure, but NOT if it is reference in the second stored procedure directly (I end up with an empty value for @statusID in this example).
My actual "Insert" stored procedures are far more complicated, but I am working towards lightening the business logic in my application ( it shouldn't have to pre-vet the data prior to executing a valid insert). 
Hopefully this makes some sense - it doesn't seem right to me that this is impossible, and am fairly sure I'm just missing some simple syntax - can anyone assist?
 

View 1 Replies View Related

@@Identity In Stored Procedure

Jun 28, 2007

Hi,I have a stored procedure  that insert data into 2 temp tables. The problem that I have is when I insert a data into a first table, how do I get the @@identity value from that table and insert it into the second table?? The following code is what I have:Create #Temp1    @StateID Identity,    @State nvarchar(2),    @wage moneyINSERT INTO #Temp1 (State, wage)SELECT State, Wage FROM Table1 INNER JOIN Table2 ON Table1.Table1_ID = Table2.Table2_IDCreate #Temp2    @ID Identity    @EmployeeID int        @StateID Int    @Field1 Money    @Field2 MoneyINSERT INTO #Temp2 (EmployeeID, StateID, Field1, Field2)SELECT EmployeeID, StateID, Field1, Field2 FROM SomeTable 

So, The first part I created a #Temp1 table and insert data into the table. Then after the insert, I want the @@Identity value and insert into the #Temp2 table. This is my first time doing stored procedure, so, I am wondering how do I retrieve the @@identity value and put into the second select statement. Please help. ahTan 

View 9 Replies View Related

Calling A Stored Procedure From ADO.NET 2.0-VB 2005 Express: Working With SELECT Statements In The Stored Procedure-4 Errors?

Mar 3, 2008

Hi all,

I have 2 sets of sql code in my SQL Server Management Stidio Express (SSMSE):

(1) /////--spTopSixAnalytes.sql--///

USE ssmsExpressDB

GO

CREATE Procedure [dbo].[spTopSixAnalytes]

AS

SET ROWCOUNT 6

SELECT Labtests.Result AS TopSixAnalytes, LabTests.Unit, LabTests.AnalyteName

FROM LabTests

ORDER BY LabTests.Result DESC

GO


(2) /////--spTopSixAnalytesEXEC.sql--//////////////


USE ssmsExpressDB

GO
EXEC spTopSixAnalytes
GO

I executed them and got the following results in SSMSE:
TopSixAnalytes Unit AnalyteName
1 222.10 ug/Kg Acetone
2 220.30 ug/Kg Acetone
3 211.90 ug/Kg Acetone
4 140.30 ug/L Acetone
5 120.70 ug/L Acetone
6 90.70 ug/L Acetone
/////////////////////////////////////////////////////////////////////////////////////////////
Now, I try to use this Stored Procedure in my ADO.NET-VB 2005 Express programming:
//////////////////--spTopSixAnalytes.vb--///////////

Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim sqlConnection As SqlConnection = New SqlConnection("Data Source = .SQLEXPRESS; Integrated Security = SSPI; Initial Catalog = ssmsExpressDB;")

Dim sqlDataAdapter As SqlDataAdapter = New SqlDataAdaptor("[spTopSixAnalytes]", sqlConnection)

sqlDataAdapter.SelectCommand.Command.Type = CommandType.StoredProcedure

'Pass the name of the DataSet through the overloaded contructor

'of the DataSet class.

Dim dataSet As DataSet ("ssmsExpressDB")

sqlConnection.Open()

sqlDataAdapter.Fill(DataSet)

sqlConnection.Close()

End Sub

End Class
///////////////////////////////////////////////////////////////////////////////////////////

I executed the above code and I got the following 4 errors:
Error #1: Type 'SqlConnection' is not defined (in Form1.vb)
Error #2: Type 'SqlDataAdapter' is not defined (in Form1.vb)
Error #3: Array bounds cannot appear in type specifiers (in Form1.vb)
Error #4: 'DataSet' is not a type and cannot be used as an expression (in Form1)

Please help and advise.

Thanks in advance,
Scott Chang

More Information for you to know:
I have the "ssmsExpressDB" database in the Database Expolorer of VB 2005 Express. But I do not know how to get the SqlConnection and the SqlDataAdapter into the Form1. I do not know how to get the Fill Method implemented properly.
I try to learn "Working with SELECT Statement in a Stored Procedure" for printing the 6 rows that are selected - they are not parameterized.




View 11 Replies View Related

Problem With @@IDENTITY In Stored Procedure

Feb 2, 2007

Hello !
I just can't access @@IDENTITY in my requests !Here is my stored procedure : (I removed a few lines for clarity)set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[AssignerLicence]
(
@Apprenant int = 0
)
AS
BEGIN
SET NOCOUNT ON;

DECLARE @NBLICENCES int
DECLARE @COMMANDEID int
DECLARE @LICENCEID int

SET @NBLICENCES = (SELECT SUM(commande_licences_reste)
FROM Commande
WHERE commande_valide = 1)

IF
@NBLICENCES > 0
BEGIN

UPDATE Commande
SET commande_licences_reste = (commande_licences_reste - 1)
WHERE commande_id =
(SELECT TOP 1 C_min.commande_id
FROM Commande AS C_min
WHERE C_min.commande_licences_reste > 5
ORDER BY C_min.commande_licences_reste ASC,
C_min.commande_date ASC);

SET @COMMANDEID = @@IDENTITY

INSERT INTO Licence (licence_date_debut, commande_id)
VALUES (GETDATE(), @COMMANDEID)

SET @LICENCEID = @@IDENTITY

UPDATE Apprenant
SET licence_id = @LICENCEID
WHERE apprenant_id = @Apprenant

END

END
But it always throws an error saying that I can't insert null into commande_id (basically, I think @@IDENTITY isn't executed at all)
Any idea why it doen't works ?
Thanks !

View 1 Replies View Related

Set Identity Not Working For Stored Procedure

Jan 31, 2008

Hi can someone tell me whats wrong with this stored procedure. All im trying to do is get the publicationID from the publication table in order to use it for an insert statement into another table. The second table PublicaitonFile has the publicaitonID as a foriegn key.
Stored procedure error: cannot insert null into column publicationID, table PublicationFile - its obviously not getting the ID.
ALTER PROCEDURE dbo.StoredProcedureUpdateDocLocField
@publicationID Int=null,@title nvarchar(MAX)=null,@filePath nvarchar(MAX)=null
ASBEGINSET NOCOUNT ON
IF EXISTS (SELECT * FROM Publication WHERE title = @title)SELECT @publicationID = (SELECT publicationID FROM Publication WHERE title = @title)SET @publicationID = @@IDENTITYEND
IF NOT EXISTS(SELECT * FROM PublicationFiles WHERE publicationID = @publicationID)BEGININSERT INTO PublicationFile (publicationID, filePath)VALUES (@publicationID, @filePath)END
 

View 5 Replies View Related

Stored Procedure And Assigning @@IDENTITY Value

Nov 3, 2003

In the following stored procedure I would like to test whether @TopCategoryID is null. If so I would like to insert the @CategoryID value into the @TopCategoryID value. So, once @CategoryID recieves the @@IDENTITY value, how do I enter this same value into @TopCategoryID as well???



CREATE PROCEDURE sp_CT_InsertCategory



@Namevarchar(50),
@Description varchar(250),
@topCategory bit,
@ParentCategoryID int,
@TopCategoryID int,
@CategoryID int OUTPUT
AS
DECLARE @CurrID int


IF @CurrID IS NULL
BEGIN

INSERT
INTO CT_Category
(CategoryName, CategoryDescription, topcategory, parentcategoryid, topcategoryid)
VALUES
(@Name, @Description, @topcategory, @ParentCategoryID, @TopCategoryID)

SET @CategoryID = @@IDENTITY

IF @@ERROR > 0
BEGIN

RAISERROR ('Insert of Category failed', 16, 1)
RETURN 99

END

END
ELSE
BEGIN

SET @CategoryID = -1

END
GO



Thanks in advance

View 9 Replies View Related

Return Identity In Stored Procedure

Mar 23, 1999

I have a stored procedure where I am passing in several strings which are concatenated to form an Insert SQL statement. I then return the identity value from the insert - problem is, the identity value is coming back NULL.

Here is the sp. Any ideas?

CREATE PROCEDURE sp_ExecuteInsert
@pIdentity int OUTPUT,
@pSQL1 varchar(255),
@pSQL2 varchar(255) = NULL,
@pSQL3 varchar(255) = NULL,
@pSQL4 varchar(255) = NULL,
@pSQL5 varchar(255) = NULL,
@pSQL6 varchar(255) = NULL,
@pSQL7 varchar(255) = NULL,
@pSQL8 varchar(255) = NULL
AS

EXECUTE (@pSQL1 + @pSQL2 + @pSQL3 + @pSQL4 + @pSQL5 + @pSQL6 + @pSQL7 + @pSQL8)

SELECT @pIdentity = @@IDENTITY
GO

FYI, the real problem I am trying to solve is simply to return the identity after an insert. I could write a simple insert sp that returns the identity, but my code is written to handle generic situations and build an INSERT statement as needed. So if there are any other ideas of executing an insert statement and getting the identity, please let me know.

Thanks...

View 4 Replies View Related

Stored Procedure Conditionally Using @@Identity

Feb 21, 2006

Im having a play using @@identity

I want to insert some data into a table

Get the AutoID value on the inserted data

then insert some other data into another table
and set its id value to the captured @@identity

My question
I only want to do the second insert only if
@FieldValue2 contains a value ie not empty

below is a basic procedure without conditonal part



Code:

CREATE PROCEDURE conditional_Insert

@FieldID As int,
@FieldValue As Nvarchar(50),
@FieldValue2 As Nvarchar(50)
AS

declare @id int

set nocount on

INSERT INTO Table1(fieldID,fieldvalue)
VALUES( @FieldID, @FieldValue)

set @id = @@identity

INSERT INTO Table2(fieldID2, FieldValue2)
VALUES(@id, @FieldValue2)

select @id
GO

View 2 Replies View Related

IDENTITY Values In A Stored Procedure

Oct 18, 2005

Hi All,
This is my stored procedure

CREATE PROCEDURE testProc AS
BEGIN
CREATE TABLE #tblTest(ID INT NOT NULL IDENTITY, Col1 INT)
INSERT INTO #tblTest(Col1)
SELECT colA FROM tableA ORDER BY colA

END


This is my simple procedure, I wanted to know whether the IDENTITY values created in #tblTest will always be consistent, I mean without losing any number in between. i.e. ID column will have values 1,2,3,4,5.....
or is there any chance of ID column having values like 1,2, 4, 6,7,8....

Please reply...
qa

View 2 Replies View Related

How To Call A Stored Procedure From A Web Page With VB

Feb 13, 2007

Dear Masters;
How can I call a stored procedure with VB code?
Thanks

View 2 Replies View Related

Sql Stored Procedure - With In Cursor Get @@identity Value For Insert And Use That Again

Jun 11, 2008

I have stored procedure which contains follwing part of it. it says syntax when i worte line to get @@identity valuewhen delete that  line command succesful. but i need to get @@identity from the insert statement and assign it to a variable and use it after
any body pls tell me how to get this within a stored prosedure or what is the error of the following code bit.  (#tblSalesOrders is a temporary table which containsset of  records from orginal table )DECLARE @soNo1 INT
 DECLARE @CursorOrders CURSOR
SET @CursorOrders = CURSOR FAST_FORWARD FOR
select fldSoNo from #tblSalesOrders
declare @newSONO1 int OPEN @CursorOrders
FETCH NEXT FROM @CursorOrders INTO @soNo1
WHILE @@FETCH_STATUS = 0
BEGIN
----for each salesorder insert to salesorderline
insert into tblSalesOrders (fldWebAccountNo,fldDescription,fldSoDate,fldGenStatus) select (fldWebAccountNo,fldDescription,fldSoDate,fldGenStatus) from #tblSalesOrders where fldSoNo =@soNo1;
 
 set @newSONO1=SCOPE_IDENTITY;
-------in this section again create another cursor for another set of records and insert to a table passing identity value return from the above insert --------------------------
SELECT @intErrorCode = @@ERRORIF (@intErrorCode <> 0) GOTO PROBLEM
FETCH NEXT FROM @CursorOrders INTO @soNo1
END CLOSE @CursorOrders
DEALLOCATE @CursorOrders

View 2 Replies View Related

Identity Column Set Not For Replication And A Stored Procedure

Feb 2, 2015

I have a table, which is being replicated with the identity column set "not for replication" and a stored procedure, which is also replicated (execution) which inserts into this table. When the execution of the stored procedure happens, the replication monitor complains about identity value not being provided.other than removing the stored procedure from replication?

View 0 Replies View Related

T-SQL (SS2K8) :: One Stored Procedure Return Data (select Statement) Into Another Stored Procedure

Nov 14, 2014

I am new to work on Sql server,

I have One Stored procedure Sp_Process1, it's returns no of columns dynamically.

Now the Question is i wanted to get the "Sp_Process1" procedure return data into Temporary table in another procedure or some thing.

View 1 Replies View Related

Connect To Oracle Stored Procedure From SQL Server Stored Procedure...and Vice Versa.

Sep 19, 2006

I have a requirement to execute an Oracle procedure from within an SQL Server procedure and vice versa.

How do I do that? Articles, code samples, etc???

View 1 Replies View Related

Stored Procedure - Page Load Slow

Jul 25, 2006

Hi all,
I have a webpage with a Datagrid that populates using a table adapter from a Stored procedure that exists in my SQL Database...If I run the Stored procedure in SQL Directly then it takes 20 Secs to return all records...If I run the webpage then it takes just over 20 Secs..
Great you say..But If I have the sorting option set in ASP.net and I click on a column to sort then off the page goes for another 20 secs to sort the data..
Is there a better way to do what I am doing here that will speed up the page load..
Ie..the data is returned once and then sorted...
Is it Better / Quicker for me to create a table using the stored procedure and link to this from the website..Updating the table every couple of minutes ?
Any advice please ?
Ray..

View 4 Replies View Related

Stored Procedure Run From ASP.NET Page Gets Very Slow Intermittently

Dec 5, 2006

I have developed a stored procedure that filters a view that is a union of several different tables. This provides status information for items across our warehouse management system. This system seems to work very well and normally processes results very quickly (< 3 seconds). However, occasionally (every few days) we begin to see timeouts on the query after 3 minutes of processing. I can watch this process in SQL Profiler and see that the query is timing out after 180 seconds, which is the timeout we have for the query within the DAL. When I copy the line from the SQL Profiler and execute it directly in SSMS, the query executes in less than 2 seconds. I first thought that somehow this had to do with execution plans, but when I try to reload the page again, which executes the query, it still times out. I did add a OPTION(KEEPFIXED PLAN) to the sproc, and that seemed to speed things up for the time, but I am not sure if this is even the problem and what the optimal solution would be. Any thoughts spring to mind?
 Thanks, Steve

View 3 Replies View Related

Is It Possible To Recieve Result Of SQL Stored Procedure To Web Page?

Jul 14, 2004

I have web server with .aspx page from wich I call stored procedure on MSSQL server. In this procedure are lots of "select" statements and I need to show results of this statements in web page. Can I call this procedure in that manner that procedure output is writen in some file and this file then ir recieved by web server and included in web page.

View 2 Replies View Related







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