Concurrency Issue In Result Returned From Stored P

Dec 11, 2007

I am working on application developed in ASP.NET 2.0 that uses lots of stored procedures from the SQL Server 2000 backend database.When the app is under load you occasionally see incorrect data returned to the page after running stored procedures.

All the stored procedures have been tested and appear to be fine. it's as if under load the returned data from the stored procedures is getting 'mixed' with another concurrent session.
Please let me know what could be the reason behind it

View 6 Replies


ADVERTISEMENT

Can A Stored Procedure's Result Set Be Returned

Apr 4, 2004

Pls give some samples

View 3 Replies View Related

Naming The Result Sets Returned By Stored Procedure

Jul 6, 2004

Greetings

I have a SQL Server stored procedure that performs several queries and therefore returns several "result sets" at any one time.

Wiring it up via ADO.NET I populate a DataSet with a number of items in the Tables collection - which is great - and I can give each item a name for identification purposes once the DataSet is populated.

But I'd like to know if there is some way I can set the names of each result set *within the text of the stored procedure*, i.e. before the DataSet gets populated.

Any help greatly appreciated.
Stuart

View 14 Replies View Related

How To Suppress Result Sets Returned From A Stored Procedure?

Aug 28, 2006

I have a novice question. How does one suppress result sets returned from a stored procedure?

I have created a procedure which makes use of multiple stored procedures . The purpose of this procedure (lets call it procA), is to count the rows returned from other procedures. The €œOther€? procedures will return rows having an unknown number of columns. I would like to limit any changes which may be needed to be made to the €œOther€? procs.

Once procA has collected all of the information (@@rowcount) from the inner procedures, then it will return a result set having several columns €“ mainly the subProcedure name and number of rows returned.

The purpose of procA is to query several subsystems and identify which ones need attention.

Cursor While Loop
exec @ProcName @ObjectName,@userID,@syncDate
set @recs = @@rowcount;


My c# program calls the sp as follows:

cmd = DataUtility.GetSQLCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "FetchAdminData";
cmd.Parameters.AddWithValue("@userID", userAlias);
cmd.Parameters.AddWithValue("@adminDate",userDate);
reader = cmd.ExecuteReader();

I do not wish to iterate over each resultSet when I am only interested in the last one. Any suggestions?



View 2 Replies View Related

Transact SQL :: Only 1st Result Being Returned?

Jun 10, 2015

We have multiple employees assigned to the same assignment sometimes, and my query is skewed as that if there are 2 people assigned to the ssame assigment I can only see the amt of time worked for the 1st person.  What should I do to remedy this?

Ouput I am receiving is

BadgeNum - Assignment -- FullName --TimeworkToday
A2323   ---- Accident Reconstruction ---- Football Helmet ---- .50
AB12 ---- Accident Reconstruction ---- Brown Shoe ---- Null
AB66 ----- Accident Reconstruction ---- Black Shoe ---- Null
ABB28 ---- Accident Reconstruction ---- White Shoe ---- Null

--And now here it's a new assignment so timeworktoday is populating

MC22 ---- Crime Prevention ---- Laptop Coputer ---- 1.13

Desired output is all employees have a value populate for timeworktoday

Declare
@count int,
@Assignment varchar(100),
@fullname varchar(100),
@timeworkedtoday decimal(18,2),
@badgeNum varchar(50)
Create Table #possibleemployees(ID INT IDENTITY NOT NULL, badgeNum varchar(50), workingtoday int)

[code]....

View 7 Replies View Related

Use Result Set Returned By Sp As Derived Table

Jun 11, 2006

Hi,I got another question here:I want to use query like this:SELECT * FROM (sp_lock AS T) WHERE objectID = ...The purpose is that I want to query the result set returned by sp_lockusing derived table, but it doesn't work. Why?Thanks,Baihao--Posted via Mailgate.ORG Server - http://www.Mailgate.ORG

View 2 Replies View Related

Can The Result From An EXEC(@sqlcommand) Be Returned To A Variable

Apr 11, 1999

Is it possible to get the result from an EXEC(@sqlcommand) statement into a variable?

As part of a SQL loop, it is necessary for me to run an EXEC() command to process an SQL statement. I have succesfully implemented this, but have been unable to get the results from the EXEC() statement into a variable to allow this data to be inserted into a table. Is this possible?

For Example (I know this doesn't work, but it is effectively what I am trying to achieve):

select @result = EXEC(@sqlcommand)

I could then use the @result variable in an insert statement to update a table with the results from the EXEC command.

Any assistance would be greatly appreciated...

Regards,
Wayne

View 2 Replies View Related

Limiting Rows Returned By Result Sets

May 20, 2008

In MySQL we use "SELECT (....) LIMIT 0, 10" to only return the first 0 to 10 records. Alternatively we could do "LIMIT 10, 20" to return the 10th to 20th records.

What's the equivilent of this in SQL Server?

Thanks

View 4 Replies View Related

Row Count Returned By A Select Query In Result

Jul 30, 2013

I want to show the number of rows returned by a select query in the result.

e.g. select policy,policynumber,datecreated,Firstname, '-' as recordcount from policy

If it returns 5 rows, then the 'recordcount' need to show '5' in all row in the result

OutPut

0y96788,HGYG564,29/07/2013,SAM,5
FJUFBN7,JLPIO67,29/07/2013,Test,5
...
..
..

How can i get this number in the result.

View 3 Replies View Related

How To Page SQL Query Result Returned From FOR XML Statement?

Apr 25, 2006

Gurus.I do not know if it is possible, but here is what I want to do.I want to allow user to page the SQL result, so he could decides toreturn from row 10 to row 20, or row 100 to 200, without returns thewhole resultset. Every time he sends another request, I do not mind tohit the database again, (I do not want to cache the result in themiddle tier server, scalability issue), and I know that I could achievethis with CURSOR, but unfortunately the FOR XML is not allowed in aCURSOR statement .(I know that I could achieve what I want to do by writing custom codein the middle tier, but I just want to see if there is a way to do thison the database side.)Any comments & suggestion is greatly appreciated.Thanks in advance.(I am using SQL2005)John

View 2 Replies View Related

Receiving There Is An Invalid Number Of Result Bindings Returned For The ResultSetType: ResultSetType_Rowset

Sep 20, 2007



I am trying to set up an Execute SQL Task that will feed into a foreach loop for processing of data. I am using an ADO.NET Connection with Direct input with full result set. I have tried using "select * from <table>" and also "select <column1>, <column2> from <table>". I have user variables set in the package and have the table cfolumn names listed in result name and the appropriate package variable in variable name on the Result Set tab. There is a total of 53 columns per row and the number of rows that should be returned can be anywhere from none to several hundred. Upon trying to run the package, I am receiving
Error: 0xC00291E2 at Execute SQL Task, Execute SQL Task: There is an invalid number of result bindings
returned for the ResultSetType: "ResultSetType_Rowset".

Anyone have any ideas here? Thanks in advance!

View 2 Replies View Related

Concurrency Handling In Stored Procedures

Jul 23, 2005

I have a requirement that requires detection of rows deleted/updated byother processes. My business objects call stored procedures to create,read, update, delete data in a SQL Server 2000 data store. I've donea fair amount of research on concurrency handling in newsgroups andother resources. Below is what I've come up as a standard forhandling concurrency thru stored procedures. I am sharing with everyoneso I can get some comments (pro/con) regarding this approach and see ifanyone can find any holes for this solution.Below is the DDL, DML and a Stored Proc demonstrating the approach. Iam using a rowversion column for concurrency checking. Another approachthat is less intrusive (doesn't require having a rowversion column inall tables) is using checksum. I may eventually use checksum but theprocess flow should be almost identical. Looking forward to anyone'scomments.Thx, BZ--xxxxxxxxxxxxxxxxxxxxxxxxxxx--IF EXISTS (SELECT * FROM sysobjects WHERE type = 'U' AND name ='ApplicationUsers')BEGINPRINT 'Dropping Table ApplicationUsers'DROP Table dbo.ApplicationUsersENDGOPRINT 'Creating Table ApplicationUsers'GOCREATE TABLE dbo.ApplicationUsers(LoginName varchar (20) NOT NULL Primary Key,LoginPassword varchar (50) NOT NULL,LoginAttempts int NOT NULL default(0),EmailAddress varchar(25) NOT NULL Unique,DataVersion rowversion NOT NULL)GOIF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name ='UpdateUser')BEGINPRINT 'Dropping Procedure UpdateUser'DROP Procedure dbo.UpdateUserENDGOPRINT 'Creating Procedure UpdateUser'GOCreate Procedure dbo.UpdateUser@loginName Varchar (20),@loginPassword Varchar (50),@loginAttempts Int,@emailAddress Varchar(25),@dataVersion Rowversion OutputAs/************************************************** ****************************** Name: dbo.UpdateUser** Desc: Updates an Application User instance**** Parameters:** Input** @loginName** @loginPassword** @loginAttempts** @emailAddress** @dataVersion. row version used for concurrency control.**** Output** @dataVersion. updated row version used for concurrencycontrol.**** Return** 0 for Success. Error code if any are encountered** 66661 if current row version doesn't match provided version** 66666 if expected row is not found**************************************************** *****************************/Set NoCount OnDeclare@err Int,@rowCount Int,@tranCount Int--Transaction HandlingSelect @tranCount = @@TRANCOUNTIf (@tranCount=0)Begin Tran LocalTranElseSave Tran LocalTranUpdatedbo.ApplicationUsersSetLoginPassword = @loginPassword,LoginAttempts = @loginAttempts,EmailAddress = @emailAddressWhereLoginName = @loginNameAndDataVersion = @dataVersion--Check for errors and rowCount (Should have updated 1 row)Select @err = @@ERROR, @rowCount = @@ROWCOUNTIf (@err != 0) GOTO ErrHandlerIf (@rowCount != 1) GOTO ConcurrencyHandler--Set dataversion output parameterSelect@dataVersion = DataVersionFromdbo.ApplicationUsersWhereLoginName = @loginName/*If we got this far then there were no errorsIf this proc started transaction then commit it,otherwise return and let caller handle transaction*/If (@TranCount = 0)Commit Tran LocalTranReturn 0/*Rollback local transaction if an error was encountered.Return code is used to communicate error number.*/--Handle Concurrency ErrorsConcurrencyHandler:Rollback Tran LocalTranIf Exists (Select * From dbo.ApplicationUsers where LoginName =@loginName)Return 66661 --Row version doesn't match provided versionElseReturn 66666 --Row not found--Handle Other ErrorsErrHandler:Rollback Tran LocalTranReturn @err --Return Err NumberGOPRINT 'Inserting Test Data...'--Add Test DataInsert Into dbo.ApplicationUsers(LoginName, LoginPassword, LoginAttempts, EmailAddress)Values('blackmamba', 'Pwd1', default, 'bm@DIVAS.com')Insert Into dbo.ApplicationUsers(LoginName, LoginPassword, LoginAttempts, EmailAddress)Values('GoGo', 'Pwd2', default, 'gogo@crazy88.com')GO/*Call UpdateUser Stored Proc with current rowversion*/Declare @retVal int, @rowvrsn rowversion--Get Current Row Versionselect @rowvrsn = DataVersion from dbo.ApplicationUsers where LoginName= 'blackmamba'Exec @retVal = dbo.UpdateUser @loginName = 'blackmamba', @loginPassword= 'UpdatedPwd', @loginAttempts = 0, @emailAddress = 'bm@DIVAS.com',@dataVersion = @rowvrsn outputPrint @retVal --Should be 0 for successGO/*Call UpdateUser Stored Proc with out of date rowversion (simulateupdate by other process)*/Declare @retVal int, @rowvrsn rowversion--Get Current Row Versionselect @rowvrsn = DataVersion from dbo.ApplicationUsers where LoginName= 'blackmamba'--Simulate update by other processUpdate dbo.ApplicationUsers Set LoginPassword = LoginPassword whereLoginName = 'blackmamba'--Update User with out of date RowversionExec @retVal = dbo.UpdateUser @loginName = 'blackmamba', @loginPassword= 'UpdatedPwdVersion2', @loginAttempts = 0, @emailAddress ='bm@DIVAS.com', @dataVersion = @rowvrsn outputPrint @retVal --Should be 66661 for rowversion mismatchGO/*Call UpdateUser Stored Proc with out of date rowversion (simulatedelete by other process)*/Declare @retVal int, @rowvrsn rowversion--Get Current Row Versionselect @rowvrsn = DataVersion from dbo.ApplicationUsers where LoginName= 'blackmamba'--Simulate delete by other processDelete From dbo.ApplicationUsers where LoginName = 'blackmamba'--Update User with out of date RowversionExec @retVal = dbo.UpdateUser @loginName = 'blackmamba', @loginPassword= 'UpdatedPwdVersion2', @loginAttempts = 0, @emailAddress ='bm@DIVAS.com', @dataVersion = @rowvrsn outputPrint @retVal --Should be 66666 for row deleted by other process

View 2 Replies View Related

SQL Server 2000 And Stored Procedure Concurrency

Apr 1, 2005

I'm using Java to connect to a SQL Server 2000 database. I connect using the Driver Manager with Sun's odbc driver ( sun.jdbc.odbc.JdbcOdbcDriver ) or I can use the jdbc driver provided by Microsoft (com.microsoft.jdbc.sqlserver.SQLServerDriver)

The Java application makes 1 Connection.

Within the database there exists a stored procedure that updates 2 Tables. The tables have a fixed number of rows that get updated continuously by calls to this stored procedure.

The Java application has a thread pool of 15 threads that create 15 CallableStatements (1 per thread) using the same instance of the Connection object.

According the the Microsoft JDBC driver docs, 1 Connection with multiple calls to the Callable statements is how it's supposed to be done. The following is an excerpt from Microsoft's "SQL Server 2000 Driver for JDBC User’s Guide and Reference" (page 86) regarding Connection Managment:
Managing Connections

Connection management is important to application performance. Optimize your application by connecting once and using multiple statement objects, instead of performing multiple connections. Avoid connecting to a data source after establishing an initial connection.
This is precisely what I'm doing, but I do not know if the the stored procedures are being run concurrently, the documentation does not tell me.

So my question: What is happening inside SQL Server 2000?

View 2 Replies View Related

Maximum Concurrency Of 2 For Outbound Network Connections From CLR-stored Procedure?

Jul 18, 2007

Hi



I've implemented an SQL-CLR stored procedure which makes an HTTP connection using the WebClient class to a server where the processing on the web server takes 10 seconds.



If I fire off a bunch of requests to the stored procedure, e.g. 80 in 1 second I noticed that SQL Server 2005 (Express Edition) only allows 2 concurrent network connections at a time.



I can confirm this by looking at the timing of the results when they come back, basically I get 2 results every 10 seconds and by doing a 'netstat -a' on the web server I notice that there are never more than 2 HTTP connections from the SQL Server at a time.



Is this some sort of sheduling policy in terms of the number of concurrent external network accesses allowed by CLR objects running in SQL Server? Or some side effect of the way the WebClient class blocks in terms of waiting for a network response?



I was expecting all 80 of the requests to block waiting on a network response almost immediately and then for all 80 of them to pretty much complete and return 10-11 seconds later.



[Microsoft.SqlServer.Server.SqlProcedure]

public static int CreditAuthorisation(string Name, decimal Amount)

{

WebClient client = new WebClient();

string result = client.DownloadString("http://someserver/Test.aspx");

return int.Parse(result);

}



Cheers

View 4 Replies View Related

How To Get The Returned Value From A Stored Procedure?

Sep 26, 2007

Hi,
I use a strong-typed DataSet to build the data access tier of my application, and the IDE generates most of code for me. However I can't find a way to get the value returned by a stored procedure(The stored procedure seems like 'RETURN 0').I noticed that a @RETURN_VALUE parameter is added automatically for each query method, but I don't know how to read the value.
Anybody could help me with the problem? Thanks.

View 2 Replies View Related

Null Result Returned Even Though IS NOT NULL Specified.

Apr 25, 2007

Hi guys,

I've got a query on a particular table returning an odd result:

SELECT DISTINCT WorkStation
FROM Invoice
WHERE WorkStation Is Not Null
ORDER BY WorkStation

This query returns the rows I'd expect plus a null row. This doesn't happen in databases at other sites, or in other tables at this site. The following query behaves as I'd expect returning only non-null AccountNumbers.

SELECT DISTINCT AccountNumber
FROM Suppliers
WHERE AccountNumber Is Not Null
ORDER BY AccountNumber

I can't reproduce these results on another site on a table of the same structure, or on another table at this site.

Any suggestions as to what might be going on?

Pertinent info:
---
select @@Version

Microsoft SQL Server 2000 - 8.00.760 (Intel X86)
Dec 17 2002 14:22:05 Copyright (c) 1988-2003 Microsoft Corporation
Standard Edition on Windows NT 5.2 (Build 3790: Service Pack 1)
---
dbcc checkdb
Abridged result:
CHECKDB found 0 allocation errors and 0 consistency errors in database 'POS'.
---
SELECT * INTO #Inv FROM Invoice

SELECT DISTINCT WorkStation
FROM #Inv
WHERE WorkStation Is Not Null
ORDER BY WorkStation

Does not reproduce this problem (and so is a probable fix) but the questions remains, what causes this?

TIA,
Karl.

View 9 Replies View Related

Incorrect Value Returned From Stored Procedure

Sep 26, 2006

I have an asp.net 1.1 website that uses sql server 2000 and vb.I have a bit of a dilema, when I run a stored procedure in a webpage it returns the wrong value, but if I run itin the query analyzer the correct value is returned. Dim orderHistory As nlb.OrdersDB = New nlb.OrdersDB

' Obtain Order ID from QueryString
Dim OrderID As Integer = CInt(Request.Params("ID"))

' Get the customer ID too
Dim myNewCustomerId As Integer = 0
myNewCustomerId = orderHistory.GetOrderCustomer(OrderID)



Public Function GetOrderCustomer(ByVal orderID As Integer) As Integer

' Create Instance of Connection and Command Object
Dim myConnection As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
Dim myCommand As SqlCommand = New SqlCommand("nlbsp_OrdersCustomerID", myConnection)

' Mark the Command as a SPROC
myCommand.CommandType = CommandType.StoredProcedure

' Add Parameters to SPROC
Dim parameterOrderID As New SqlParameter("@order_id", SqlDbType.Int, 4)
parameterOrderID.Value = orderID
myCommand.Parameters.Add(parameterOrderID)

Dim parameterOrderCustID As New SqlParameter("@customer_id", SqlDbType.Int, 4)
parameterOrderCustID.Value = ParameterDirection.Output
myCommand.Parameters.Add(parameterOrderCustID)

'Open the connection and execute the Command
myConnection.Open()
myCommand.ExecuteNonQuery()
myConnection.Close()

' Return the customer_id (obtained as out paramter of SPROC)

If parameterOrderCustID.Value <> 0 Then
Return CInt(parameterOrderCustID.Value)
Else
Return 0
End If

End Function


the stored procdure is
CREATE PROCEDURE [dbo].[nlbsp_OrdersCustomerID]
(
@order_id int,
@customer_id int OUTPUT
)
AS

/* Return the customer_id from the Orders. */
SELECT
@customer_id = customer_id

FROM
nlb_Orders

WHERE
order_id = @order_id
GO

 I know a particular order_id returns a value of 1. But when I run it in the webpage it always comes back as 2. Any ideas would be appreciated ThanksPete

View 1 Replies View Related

Stored Procedure - Too Many Rows Returned

Jan 12, 2007

The following query only brings back too much data in the table - there are duplicates and the lab it shows is wrong.
The problem is:  
AND a.calLab = f.ID
in the Where statement.
Some equipment does not need calibration, so, a.calDueDate = 0 AND a.calLab would be NULL or 0.
tblLabs ID field has 1 - 18 (Labs) - no 0 and of course no null
I need to get the rest of the data.
Any suggestions?
Thanks.....
Zath
 
SELECT a.assignedID,
b.Manufacturer,
a.modelNumber,
a.serialNumber,
e.equipmentType,
a.Description,
c.Location,
d.Status,
a.modifiedDate,
a.modifiedBy,
a.Notes,
a.Picture,
f.LabName,
a.calibrationRequired,
a.calDate,
a.CalDueDate,
a.assetNumber,
a.ID
FROM tblEquipments a,
tblManufacturers b,
tblLocation c,
tblStatus d,
tblEquipment_Type e,
tblLabs f
WHERE a.manufacturer = b.manufacturerID
AND a.location = c.locationID
AND a.Status = d.statusID
AND a.EquipmentType = e.ID
AND (a.calLab = f.ID or a.calLab Is NULL or a.calLab = 0)   
   ORDER BY a.ID
 
 

View 1 Replies View Related

Stored Procedure && Returned Values

Dec 23, 2007

I have a stored procedure that selects * from my table, and it seems to be working fine:
 USE myDB
GO
IF OBJECT_ID ( 'dbo.GetAll', 'P') IS NOT NULL
DROP PROCEDURE GetAll
GO
CREATE PROCEDURE GetAll
AS
DECLARE ref_cur Cursor
FOR
SELECT * FROM myTable
Open ref_cur
FETCH NEXT FROM ref_cur
DEALLOCATE ref_cur
 
The problem is, I'm trying to create a DB class, and I'm not sure what Parameter settings I'm supposed to use for my returned values.  Can anyone help me finish this?public class dbGet_base
{
public dbGet_base()
{
_requestId = 0;
}

public dbGet_base(Int64 RequestId)
{
this._requestId = RequestId;
getDbValues(RequestId);
}
public void getDbValues(Int64 RequestId)
{
getDbValues(RequestId, "GetAll");
}
public void getDbValues(Int64 RequestId, string SP_Name)
{
using(SqlConnection Conn = new SqlConnection(ConfigurationManager.AppSettings["WSConnection"]))
using (SqlCommand Command = new SqlCommand(SP_Name, Conn))
{
Command.CommandType = CommandType.StoredProcedure;
Command.Parameters.Add("@Request_Id", SqlDbType.Int).Value = RequestId;
Command.Parameters.Add(??
}

View 3 Replies View Related

Stored Procedure Works But Nothing Returned?

Mar 4, 2004

Hello,

I have the following stored prod in SQL server:

CREATE PROC spValidateUserIdAndPassword

@UserIdvarchar(50),
@Passwordvarchar(50)
AS
SELECT tblAdvertisers.UserID, tblAdvertisers.Password
FROM tblAdvertisers
WHERE ((tblAdvertisers.UserID = @UserId) AND (tblAdvertisers.Password = @Password))


I can run it in Query Analyzer and it returns one record as it should. I want it in ASP.NET to return the amount of rows that are effected, e.g that the login is correct.

The code I have is:


public bool ValidateUserIdAndPassword(string userId, string password)
{
sqlCommand.CommandType = CommandType.StoredProcedure;
//the name of the stored procedure
sqlCommand.CommandText = "spValidateUserIdAndPassword";

SqlParameter myParam;

//add the param's to the SP

//userId information for the user
myParam = new SqlParameter("@UserId", SqlDbType.VarChar, 50);
myParam.Value = CStr(userId);
sqlCommand.Parameters.Add(myParam);

//password information for the user
myParam = new SqlParameter("@Password", SqlDbType.VarChar, 50);
myParam.Value = CStr(password);
sqlCommand.Parameters.Add(myParam);

try
{
int rows = sqlCommand.ExecuteNonQuery();

if(rows == 1)
return true;
else
return false;

}
catch(System.Exception er)
{
//for design time error checking
return false;
}



This returns -1...

Please help me

Kind Regards


KitkatRobins :-)

View 3 Replies View Related

Trying To Retrieve A Value Returned By A Stored Procedure

Apr 30, 2006

I have a stored procedure that return either 1 or -1 : IF EXISTS( ) BEGIN return 1 ENDELSE BEGIN return -1 ENDAnd then I try to retrieve the returned value by doing this:int value = Convert.ToInt32(command.ExecuteScalar());But the value I get is always 0. Anyone see what is wrong?  

View 1 Replies View Related

Stored Procedure Syntax - Value Not Returned

Feb 5, 2004

I have the following stored procedure. The good thing is I finally got the syntax to the point where it doesn't blow up, but I was under the impression the "print" statement would print my result. In this case all I get is the statement ' 1 Row Affected ' which by the way is not the answer I was expecting.

Here's the code:
'
CREATE PROCEDURE createevents
AS

declare @myvariable varchar(700)

declare @myvar varchar(700)

begin
Select @myvariable = d.id
from table1 d, table2 dc where d.class = dc.class

If @myvariable > 0
begin
Select @myvar =dp. class
from table3 dp, table2 dc
where dp.class = dc.class

If @myvariable >= 1
begin
print @myvariable + (',') + @myvar
end
end

else
begin
print @myvariable + ('is empty')
end
end

'
Thanks in advance for any help.

View 5 Replies View Related

SQL 2012 :: Getting Returned Value Of A Stored Procedure?

Jun 2, 2015

I am running a sproc we have developed and I am getting a -6 as a returned value.what that actually means.

View 7 Replies View Related

Value That Is Returned If An Insert Is Not Performed From A SQL Stored Procedure.

Sep 14, 2007

I am using the following stored procedure to insert a value into the database. I am new to stored procedures so I need help. Basically this stored procedurewill only insert a value for "CustomerName" if it is not a duplicate value.
So I noticed in My C# when I call this stored procedure, a negative one "-1"is returned if the insert is not performed because of a duplicate value.
Is that correct? Should I be getting back a negative one "-1" ? You seeI thought that a Zero "0" would be returned if the insert was not performed.Not a negative one?
SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGO
CREATE PROCEDURE [dbo].[CustomerCreate](  @CustomerDescription nvarchar(100),  @CustomerName nvarchar(100),  @LastUpdateDate datetime,  @LastUpdateUser nvarchar(32),  @inserted_record smallint output)
AS
 if exists (select 1 from Customer where CustomerName = @CustomerName) BEGIN
    set @inserted_record = 0
 END    ELSE BEGIN INSERT INTO Customer (  CustomerDescription,  CustomerName,        Active,  LastUpdateDate,  LastUpdateUser ) VALUES (  @CustomerDescription,  @CustomerName,  @LastUpdateDate,  @LastUpdateUser ) END

View 5 Replies View Related

If Exists Capture Value Returned From Stored Proc

Feb 26, 2006

I have a stored proc with a query which checks whether an identical
value is already in the database table. If so, it returns a value of 1.
How do I caputure this value in an asp.net page in order to display a
message accordingly? (using ASP.NET 1.1)

Currently my stored proc looks something like this (snippet only):
If Exists(
SELECT mydoc WHERE....
)
Return 1
Else
...INSERT INTO.... code here.

View 2 Replies View Related

Reading Values Returned From A Stored Procedure

Nov 10, 2000

I am trying to use a stored procedure inside the scripter in a site server pipeline. Can anyone tell me how the scripter will read the the result which is a variable. The stored procedure is returning the right value when run in query analyzer but I don't know how to retrieve it inside the pipeline.

Thank you
JG

View 1 Replies View Related

Append Recordset Returned From A Stored Procedure

May 12, 2004

I have a recordset returned from a stored procedure executed in the form open event. Could this recordset append to the form's recordsource property in the form's open event in VB? if so, what's the syntax?

Private Sub Form_Open(Cancel As Integer)
dim ...

Set add_bag_results = Nothing
With add_bag_results
.ActiveConnection = CurrentProject.Connection
.CommandType = adCmdStoredProc
.CommandText = "spSampling_add_bag_results"
.Parameters.Append .CreateParameter("ret_val", adInteger, adParamReturnValue)
'.Parameters.Append .CreateParameter("@lotnum", adInteger, adParamInput, 4, rs_add_bag_results(1))
.Parameters.Append .CreateParameter("@lotnum", adInteger, adParamInput, 4, lot_n)
..
Set rs_add_bag_results = .Execute
End With

Me.RecordSource = rs_add_bag_results ?

Thanks!

View 2 Replies View Related

Convert Stored Procedure's Returned Output To Varchar From Int?

Jun 23, 2006

I have 1 files, one is .sql and another is stored procedure. SQL file will call the stored procedure by passing the variables setup in the SQL file. However, everything ran well except at the end, I try to get the return value from SP to my SQL file ... which will send notification email. But, I get the following msg ... I am not sure how to fix this ... help!!! :(
Syntax error converting the varchar value 'ABC' to a column of data type int.
SQL file
======================
DECLARE @S AS VARCHAR(1000)
EXEC @S = PDT.DBO.SP_RPT     'ABC'
SELECT CONTENT = @S  -- this is the value I am trying to pass as content of the email
EXEC PRODUCTION.DBO.SENDEMAIL 'xxx@hotmail.com', 'Notification', @S
======================
Stored Procedure
======================
CREATE procedure sp_RPT( @array varchar(1000) ) AS
DECLARE @content AS VARCHAR(2000)
SET @content = 'RPT: ' + @array + ' loaded successfully '
SET @array = 'ABC'RETURN CONVERT(VARCHAR(1000),@array)
GO

View 2 Replies View Related

Validation Of Returned Order Of Fields From A Stored Proc

Jul 17, 2006

Hi,
Can we validate the returned order of fields from a stored procedure? Infact, i am taking a query as user input and extracts the results based on the query but for that order of fields specified in a query is important.
Can i check the order after the query is run i.e if this is entered "select field1,field2,field3 from table" then i need to check the order of the resultset generated. I can't check the query before the resultset is generated because a user can enter bunch of queries.
Any way will work, tsql or .net app.
Thanks,
 

View 3 Replies View Related

Stored Procedure/results Returned Double Problem

Oct 18, 2006

Stored Procedure ProblemThis is probably a simple problem but i would appreciate some help.I have a stored procedure that takes the order date time plus other information fromvarious tables but the information is being returned double:ie 4 rows are being returned instead of two. Can anyone see where i am going wrong?Many thanksMartinThis is the stored procedureALTER PROCEDURE dbo.SP_RetrieveOrdersASSELECT distinct OD.DateCreated, O.OrderID,O.UserID,O.OrderTotal,O.Sent,O.Delivered,O.Paid,C.CustomerNameFROM Orders As O,Customers As C,OrderDetails as ODWHERE O.UserID=C.UserID And O.OrderTotal  >0 RETURNThese are the results that are returnedDateCreated             OrderID     UserID                               OrderTotal       Sent   Delivered Paid   CustomerName               ----------------------- ----------- ------------------------------------ ---------------- ------ --------- ------ --------------- 18/10/2006 14:49:00     41          7A2E2B9B-57FA-4329-B4BB-D7ED965AA183 500              <NULL> <NULL>    <NULL> bill                     18/10/2006 14:49:00     42          7A2E2B9B-57FA-4329-B4BB-D7ED965AA183 590              <NULL> <NULL>    <NULL> bill                     18/10/2006 15:05:00     41          7A2E2B9B-57FA-4329-B4BB-D7ED965AA183 500              <NULL> <NULL>    <NULL> bill                      18/10/2006 15:05:00     42          7A2E2B9B-57FA-4329-B4BB-D7ED965AA183 590              <NULL> <NULL>    <NULL> bill                     No rows affected.(4 row(s) returned)If I leave OD.DateCreated ie use ALTER PROCEDURE dbo.SP_RetrieveOrdersASSELECT distinct O.OrderID,O.UserID,O.OrderTotal,O.Sent,O.Delivered,O.Paid,C.CustomerNameFROM Orders As O,Customers As C,OrderDetails as ODWHERE O.UserID=C.UserID And O.OrderTotal  >0 RETURNthen there is no problem. I get:41          7A2E2B9B-57FA-4329-B4BB-D7ED965AA183 500              <NULL> <NULL>    <NULL> bill                     42          7A2E2B9B-57FA-4329-B4BB-D7ED965AA183 590              <NULL> <NULL>    <NULL> bill                     No rows affected.(2 row(s) returned) 

View 2 Replies View Related

Running Returned Results Through A Stored Procedure All In One Trip

Nov 6, 2006

Hi,
I need to write a select query that will run all returned results through a separate stored procedure before returning them to me.
Something like....
SELECT TOP 10 userid,url,first name FROM USERS ORDER by NEWID()
......and run all the selected userids through a stored procedure like.....
CREATE PROCEDURE AddUserToLog (@UserID int ) AS INSERT INTO SelectedUsers (UserID,SelectedOn) VALUES (@UserID,getdate())
 Can anyone help me to get these working togethsr in the same qurey?
 
Thanks

View 7 Replies View Related

Limit The Number Of Records Returned In Stored Procedure.

Aug 17, 2007

In my ASP page, when I select an option from the drop down list, it has to get the records from the database stored procedure. There are around 60,000 records to be fetched. It throws an exception when I select this option. I think the application times out due to the large number of records. Could some tell me how to limit the number of rows to be returned to avoid this problem. Thanks.
 Query
SELECT @SQLTier1Select = 'SELECT * FROM dbo.UDV_Tier1Accounts WHERE CUSTOMER IN (SELECT CUSTOMERNUMBER FROM dbo.UDF_GetUsersCustomers(' + CAST(@UserID AS VARCHAR(4)) + '))' + @Criteria + ' AND (number IN (SELECT DISTINCT ph1.number FROM Collect2000.dbo.payhistory ph1 LEFT JOIN Collect2000.dbo.payhistory ph2 ON ph1.UID = ph2.ReverseOfUID WHERE (((ph1.batchtype = ''PU'') OR (ph1.batchtype = ''PC'')) AND ph2.ReverseOfUID IS NULL)) OR code IN (SELECT DISTINCT StatusID FROM tbl_APR_Statuses WHERE SearchCategoryPaidPaymentsT1 = 1))'

View 2 Replies View Related

Data Returned From .WriteXML Is Different Than What Is Returned In Query Analyzer.

Jun 20, 2006

I have a strange problem. I have some code that executes a sql query. If I run the query in SQL server query analyzer, I get a set of data returned for me as expected. This is the query listed on lines 3 and 4. I just manually type it into query analyzer.
Yet when I run the same query in my code, the result set is slightly different because it is missing some data. I am confused as to what is going on here. Basically to examine the sql result set returned, I write it out to an XML file. (See line 16).
Why the data returned is different, I have no idea. Also writing it out to an XML file is the only way I can look at the data. Otherwise looking at it in the debugger is impossible, with the hundreds of tree nodes returned.
If someone is able to help me figure this out, I would appreciate it.
1. public DataSet GetMarketList(string region, string marketRegion)2. {3.   string sql = @"SELECT a.RealEstMarket FROM MarketMap a, RegionMap b " + 4."WHERE  a.RegionCode = b.RegionCode"; 5.   DataSet dsMarketList = new DataSet();6.   SqlConnection sqlConn = new SqlConnection(intranetConnStr);   7.   SqlCommand cmd = new SqlCommand(sql,sqlConn);8.  sqlConn.Open();9.   SqlDataAdapter adapter = new SqlDataAdapter(cmd); 10.   try11.   {12.   adapter.Fill(dsMarketList);
 13.  String bling = adapter.SelectCommand.CommandText;//BRG 14.   dsMarketList.DataSetName="RegionMarket"; 15.  dsMarketList.Tables[0].TableName = "MarketList"; 16.    dsMarketList.WriteXml(Server.MapPath ("myXMLFile.xml" )); // The data written to  17. myXMLFile.xml is not the same data that is returned when I run the query on line 3&4 18.           // from the SQL query 19.  } 20.  catch(Exception e) 21. {  22. // Handle the exception (Code not shown)

View 2 Replies View Related







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