Stored Proc Returning Dataset && Number Of Records Not Working

Jul 7, 2004

Hi





I've created a sproc in SQL2000 that returns a dataset from a temp table & the number of records it's returning as an output parameter, although I can't seem to retrieve the value it's returning in asp.net although I get the dataset ok.





This is my sproc


create procedure return_data_and_value


@return int output


as


set nocount on


...


...


select * from #Table


select @return = count(*) from #Table


drop table #Table


go





This is asp.net code





Dim nRecords as Int32


Dim cmd As SqlCommand = New SqlCommand("return_data_and_value", conn)


cmd.CommandType = CommandType.StoredProcedure





Dim prm As SqlParameter = New SqlParameter("@return", SqlDbType.Int)


prm.Direction = ParameterDirection.Output


cmd.Parameters.Add(prm)





conn.Open()





dr = cmd.ExecuteReader





nRecords = convert.int32(cmd.parameters(@return).value)





conn.close








Thanks


Lbob

View 1 Replies


ADVERTISEMENT

Proc Returning All Records

Nov 17, 2006

Following Proc is returning all records.I have passed any value to parameters but no luck.


CREATE PROCEDURE GetAllUsers(
@persontype varchar(100)="",
@name varchar(100)="",
@adddatetime datetime="",
@activeaccount int =-1,
@country varchar (20)=""
)
AS
declare @cond varchar(1000) ;

if @persontype<>""
begin
set @cond= @cond+"and persontype="+@persontype
end
if @name<>""
begin
set @cond= @cond+"and (charindex("+@name+",x_firstname)>0 or charindex("+@name+",x_lastname)>0 or charindex("+@name+",x_email)>0) "
end
if @activeaccount<>-1
begin
set @cond= @cond+'and activeaccount='+@activeaccount
end
if @adddatetime<>""
begin
set @cond= @cond+'and adddatetime='+@adddatetime
end
if @country<>""
begin
set @cond= @cond+'and x_country='+@country
end
print @cond
exec( " select * from users where 1=1 "+@cond)
GO



zx

View 2 Replies View Related

Returning Limited Number Of Records!

Jul 8, 2004

I am using ORDER BY NEWID() to return random record from sql database. how do i go about returning only 5 random records instead of all records.

Thanks.

View 2 Replies View Related

Returning Number Of Records Found In Query

Jan 24, 2008

I am trying to return the number of records found by the query but keep seeing -1 in label1. This query should return many records.
         sub findcustomers(sender as object,e as eventargs)            dim connection1 as sqlconnection=new sqlconnection(...)            dim q1 as string="select * from tblcustomers where store='65'"            dim command1 as sqlcommand=new sqlcommand(q1,connection1)            dim a as integer            command1.connection.open()            a=command1.executenonquery()            label1.text=a.tostring()            command1.connection.close()         end sub
What am I doing wrong?

View 8 Replies View Related

Stored Procedure Returning Dataset

Sep 26, 2014

ALTER PROCEDURE [dbo].[getFavoriteList]
as
begin
SET NOCOUNT ON
select manufacturer_name from dbo.Favorite_list
end

execute getFavoriteList

It reruns infinite data and finally i got message as

Msg 217, Level 16, State 1, Procedure getFavoriteList, Line 15
Maximum stored procedure, function, trigger, or view nesting level exceeded (limit 32).

I am trying to return the dataset from stored procedure.

View 1 Replies View Related

Returning Recordset From Stored Proc

Mar 7, 2008

I need to return a rowset from a stored procedure.  The returned rows will have ten columns and need to be bound to a gridview.  Here is a code snippet.
'Create a DataAdapter, and then provide the name of the stored procedure.MyDataAdapter = New SqlDataAdapter("TMPTABLE_QUERY", MyConnection)
'Set the command type as StoredProcedure.
MyDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure
'Create and add a parameter to Parameters collection for the stored procedure.MyDataAdapter.SelectCommand.Parameters.Add(New SqlParameter("@condition_cl", _
SqlDbType.VarChar, 100))
'Assign the search value to the parameter.MyDataAdapter.SelectCommand.Parameters("@condition_cl").Value = sqlwhere & orderby
'ASSIGN THE OUTPUT PARAMETERS. HERE IS WHERE I NEED HELP  (?????????????????)
 
DS = New DataSet() 'Create a new DataSet to hold the records.
MyDataAdapter.Fill(DS, "TMPTABLE_QUERY") 'Fill the DataSet with the rows returned.
'Set the data source for the DataGrid as the DataSet that holds the rows.GridView1.DataSource = DS.Tables("TMPTABLE_QUERY").DefaultView
GridView1.DataBind()
MyDataAdapter.Dispose() 'Dispose of the DataAdapter.
MyConnection.Close()
 
In my little research, I have seen examples of how to return a single value, but not multiple rows.  I essentially have two problems.  I'm not sure how my output parameters are to be defined and added.  Do I need a separate 'Parameters.Add' statement for each column field value returned or can I do a single 'Parameters.Add' statement to define the whole row as an output parameter?  Also, upon returning from the call to the SP, will I need a looping mechanism to populate the recordset for each individual record returned, or will the 'MyDataAdapter.Fill(DS, "TMPTABLE_QUERY") suffice, as included in my code above?
Thanks in advance.

View 3 Replies View Related

Stored Proc Returning 0 Size

Mar 3, 2004

i have a stored proc


CREATE PROCEDURE pop_notes ( @contnum as bigint,@cusnotes varchar(1000) OUTPUT) as

begin

declare @noteid as int
select @noteid=max(noteid) from cusaddnotes where contractnum=@contnum and rtrim(popup)='yes'
if @noteid > 0
begin
select @cusnotes=(notes + ' [' + convert(varchar(100),dateadded) + ']' ) from cusaddnotes where noteid =@noteid

end
else
begin
set @cusnotes='none'
end
print @cusnotes
end
GO


the srored proc is returning the @cusnotes with a size 0 and its throwing out errors in my asp.net page

'@cusnotes' of type: String, the property Size has an invalid size: 0

i tried to run the stored proc frm the QA

declare @note as varchar(1000)
exec @note=pop_notes 3430,'y'
print @note



it returned

none
0 <-- this seems to be causing the error


what could be the error/reason...

thanks in advance

View 3 Replies View Related

Returning @@IDENTITY FROM Stored Proc

Nov 15, 2005

I am trying to get the identity of an inserted record using this SP:

<code>
ALTER PROCEDURE acereal_Admin.AuctionInsertCommand
(
    @AuctionID Int OUTPUT,
    @StartDate char(255),
    @StartTime char(255),
    @Location char(255),
    @Title char(255),
    @Description char(255),
    @Images char(255)
)
AS
INSERT INTO Auctions
(
    StartDate,
    StartTime,
    Location,
    Title,
    Description,
    Images
)
VALUES
(
    @StartDate,
    @StartTime,
    @Location,
    @Title,
    @Description,
    @Images
)

SELECT     AuctionID AS ID
FROM         Auctions
WHERE     (AuctionID = @@IDENTITY)
</code>

Then, I am using this class for a file called dataaccess.cs to return the ID:

<code>
public string SaveImageName(string ImageName, string AuctionID)
        {
            SqlConnection
sqlConnection = new
SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);

           
this.newSqlCommand = new
System.Data.SqlClient.SqlCommand("[AuctionImageSave]", sqlConnection);
           
this.newSqlCommand.CommandType =
System.Data.CommandType.StoredProcedure;

            SqlParameter
paramImagePath = new System.Data.SqlClient.SqlParameter("@ImagePath",
System.Data.SqlDbType.Char, 255);
            paramImagePath.Value = ImageName;
            this.newSqlCommand.Parameters.Add(paramImagePath);

            SqlParameter
paramAuctionID = new System.Data.SqlClient.SqlParameter("@AuctionID",
System.Data.SqlDbType.Int, 4);
            paramAuctionID.Value = AuctionID;
            this.newSqlCommand.Parameters.Add(paramAuctionID);

            SqlParameter
paramImageID = new System.Data.SqlClient.SqlParameter("@ImageID",
System.Data.SqlDbType.Int, 4);
            paramImageID.Direction = ParameterDirection.Output;
            this.newSqlCommand.Parameters.Add(paramImageID);

            //Return SqlDataReader Struct
            this.newSqlCommand.Connection.Open();
            this.newSqlCommand.ExecuteNonQuery();
            this.newSqlCommand.Connection.Close();

            int returnID = (int)paramImageID.Value;

            return returnID.ToString();
        }
</code>

The above code returns null.

Can anyone tell me what I am doing wrong?

THanks, Justin.

View 2 Replies View Related

Returning Errors From Stored Proc

Feb 5, 2007

Hi,

Does sql server return an error code when a stored procedure fails, or an operation inside a stored procedure fails. How does one trap it?

We have an application that executes a number of stored procedures. I would like to verify that the procedures executed successfully, and the operations contained within the stored procedures (i.e. insert into a table) did not result in an error. If there was an error with the stored procedure of the operations inside, I would like to trap it, and return it to the calling program (non sql server).

I have seen the @@error global variable, but it only gives the return code of the last operation, which means I would have to check after every select, insert, delete, etc. I am hoping to avoid this.

Any thoughts?

Thanks in advance

View 2 Replies View Related

Returning A Value From Stored Proc With Query

Jul 18, 2014

In some of our business object reports we have to create variables to decode values to what we want. I am trying to replicate this in SQL Server and remember doing this in SQL server 2000 years ago back can't remember the exact way to do it. I remember running a query and calling stored proc within query which would return the value I wanted but not sure if I can still do this in SQL server 2008 and by that I mean doing it within query or have to do it another way.

Basically what I want is to have a procedure with all the variables replicated within that procedure so that when I run a query I can just call the appropriate bit of code by passing a specific name like

select job.dept, dbo.decodevariable('ShowJobDesc' job.jobtitle), job.salary
from job

so 'ShowJobDesc' and the job.jobtitle would be used to decode each job title to return job description.Just a bit unsure and can't remember if I am doing this the right way, is this possible?

View 2 Replies View Related

SQL Stored Proc Not Returning Any Data In The Web Page

Feb 26, 2007

Hi
I have coded the simple login page in vb .net  which calls the stored proc to verify whether the user login details exists in the database.  The stored procudure returns data back when I execute it in the SQL SERVER Management studio. But when I  execute the stored proc in the 'Run stored Proc' wizard' , it is not retuning any data back. Connection string works fine as another SQL select command returns data in the same page.. I have included the VB code . Please help me to sort out this problem.Thank you.
 
If Not ((txtuser.Text = "") Or (txtpassword.Text = "")) Then
 
 
Dim conn As New SqlConnection()
conn.ConnectionString = Session("constr")
conn.Open()
 
Dim cmd As New SqlCommand("dbo.CheckLogin", conn)
cmd.CommandType = CommandType.StoredProcedure
' Create a SqlParameter for each parameter in the stored procedure.
Dim usernameParam As New SqlParameter("@userName", SqlDbType.VarChar, 10)
usernameParam.Value = Trim(txtuser.Text)
 
Dim pswdParam As New SqlParameter("@password", SqlDbType.NVarChar, 10)
pswdParam.Value = Trim(txtpassword.Text)
 
Dim useridParam As New SqlParameter("@userid", SqlDbType.NChar, 5)
Dim usercodeParam As New SqlParameter("@usercode", SqlDbType.VarChar, 10)
Dim levelParam As New SqlParameter("@levelname", SqlDbType.VarChar, 50)
 
'IMPORTANT - must set Direction as Output
useridParam.Direction = ParameterDirection.Output
usercodeParam.Direction = ParameterDirection.Output
levelParam.Direction = ParameterDirection.Output
 
'Finally, add the parameter to the Command's Parameters collection
cmd.Parameters.Add(usernameParam)
cmd.Parameters.Add(pswdParam)
cmd.Parameters.Add(useridParam)
cmd.Parameters.Add(usercodeParam)
cmd.Parameters.Add(levelParam)
 
Dim reader1 As SqlDataReader
Try
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Try
reader1 = cmd.ExecuteReader
Using reader1
 
If reader1.Read Then
Response.Write(CStr(reader1.Read))
Session("userid") = reader1.GetValue(0)
Session("usercode") = CStr(usercodeParam.Value)
Session("level") = CStr(levelParam.Value)
Server.Transfer("home.aspx")
Else
ErrorLbl.Text = "Inavlid Login. Please Try logging again" & Session("userid") & Session("usercode") & Session("level")
End If
End Using
Catch ex As InvalidOperationException
ErrorLbl.Text = ex.ToString()
End Try
Finally
If conn.State <> ConnectionState.Closed Then
conn.Close()
End If
 
End Try
 
Else
ErrorLbl.Text = "Please enter you username and password"
 
 
 
End If
 

View 5 Replies View Related

Returning Mutliple Strings From Stored Proc

May 14, 2007

Hey guys, could somebody pls provide me with an easy example as to how you would return multiple strings from a stored proc? Even a link to a decent tut would be great!

Muchos gracias!

View 12 Replies View Related

Transact SQL :: Stored Procedure Not Returning Dataset (No Columns Are Coming)

Jun 3, 2015

We are facing an issue while executing a stored procedure which uses a table of current database with INNER JOIN a table of another database in same instance.

Per our requirement, we are inserting select statement output in table variable. Then applying business logic and finally showing the data from table variable.

This scenario is working exactly fine in Dev environment. But when we deployed the code in quality environment. Stored procedure does not returning OUTPUT/ (No column names) from table variable.

During initial investigation, we found that collation of these two databases are different but we added DATABASE_DEFAULT collation in the JOIN.

View 14 Replies View Related

Integration Services :: Creating A Column With Total Number Of Records In Dataset For Each Row?

Aug 17, 2015

I have a transformation where final result set give me 25 rows of data. Now before I put into destination table, I need to add another column which will show how many total records we have. Like.

My dataset:

A  20 abc
B 24 mnp
c 44 apq

Now I need to add another column within my transformation before I store the result set to destination like this:

A 20 abc 3
b 24 mnp 3
c 44 apq 3

Here. new column gives count of total rows in our dataset which was 3.

How can I achieve this? Can I use derive column to this?

View 6 Replies View Related

Call To Stored Proc Returning Null Datatable

Jun 6, 2007

I have a stored proc which should be returning a datatable.  When I execute it manually it returns all requested results. However, when I call it via code (C#) it is returning a null table which leads me to believe the problem is in my code.  I'm not getting any errors during runtime.  Any help at all would be a BIG help!
private void PopulateControls()    {        DataTable table = CartAccess.getCart();    }
public static DataTable getCart() {        DbCommand comm = GenericDataAccess.CreateCommand();        comm.CommandText = "sp_cartGetCart";
        DbParameter param = comm.CreateParameter();        param.ParameterName = "@CartID";        param.Value = cartID;        param.DbType = DbType.String;        param.Size = 36;        comm.Parameters.Add(param);
        DataTable table = (GenericDataAccess.ExecuteSelectCommand(comm));        return table; }
public static DataTable ExecuteSelectCommand(DbCommand command)    {        // The DataTable to be returned         DataTable table;        // Execute the command making sure the connection gets closed in the end        try        {            // Open the data connection             command.Connection.Open();            // Execute the command and save the results in a DataTable            DbDataReader reader = command.ExecuteReader();            table = new DataTable();            table.Load(reader);            // Close the reader             reader.Close();        }        catch (Exception ex)        {            Utilities.SendErrorLogEmail(ex);            throw ex;        }        finally        {            // Close the connection            command.Connection.Close();        }        return table;    }

View 1 Replies View Related

SELECT Returning Multiple Values In A Stored Proc

Jul 20, 2005

HiI'm not sure what the best approach for this is:I have a stored procedure which I would like to use to return severaloutput values instead of returning a recordset.CREATE PROCEDURE Test (@param1 int, @param2 int OUTPUT, @param3 intOUTPUT) ASSELECT field2, field3 FROM Table WHERE field1 = @param1I would like to return @param2 as field2 and @param3 as field3How do I do this without using SELECT multiple times?THanks in advanceSam

View 6 Replies View Related

Openrowset In Stored Proc Returning 'S:' Is Not A Valid Path

Nov 2, 2007

I am having a difficult time figuring this one out. I have a stored procedure that as part of an ASP.Net app connects to a csv file through a mapped network drive and imports the data into a table in SQL Server. Here it is.

------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[usp_ImportComp]

-- Add the parameters for the stored procedure here
@CSV as varchar(255)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
Begin Try
Begin Tran
Declare @sql as nvarchar(max)
Set @SQL = 'Insert into dlrComp ( SN,
CM,
PM,
MC,
Comp_Total,
XU,
GM,
From_Date,
To_Date)
Select [Serial Number],
CM,
PM,
MC,
[Comp Total],
XU,
GM,
[From Date],
[To Date]
FROM OPENROWSET(' + char(39) + 'MICROSOFT.JET.OLEDB.4.0' + char(39) + ',' + char(39) + 'Text;Database=S:' + char(39) + ',' + char(39) + 'SELECT * FROM ' + @csv + char(39) + ')'
--print @sql
Exec sp_executesql @stmt=@sql
Commit Tran
End Try
Begin Catch
Rollback Tran
--Do some logging and stuff here
End Catch
END

------------------------------------------------------------------------------------

If I am connected to SQL through SQL Management Studio while logged in on the server that is running SQL as DomainUser1 and execute

exec usp_ImportComp @CSV='Comp.csv'

It completes successfully

However if I open SSMS (while logged into Windows on my PC as DomainUser2) using runas to run it as DomainUser1 while logged into my PC and connect to SQL Server using WIndows Auth and run the same I get the following error message.

OLE DB provider "MICROSOFT.JET.OLEDB.4.0" for linked server "(null)" returned message "'S:' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides.".

If I add
With Execute as 'DomainUser1' and modify the stored procedure I get the same error message above.

If I log onto the Server that is running SQL as DomainUser2 I can successfully run

exec usp_ImportComp @CSV='Comp.csv'

Both User1 and User2 have the same permissions to the Share and csv as does the Domain user under whose context SQL Server is running.

What am I doing wrong?

View 4 Replies View Related

Dataset Using Stored Proc With Multi Select Params

Aug 7, 2007

I have a stored proc that I'm using to run a report. It works fine, but currently I'm using a parameter that is a single selection from a dropdown. I'd like to use multi select, but have not been able to get it to work.

In the data tab I'm currently using "text" for command type and :





Code Snippet

declare @sql nvarchar(2000)

set @sql = '
EXEC [Monitor] '' + @p_OfferStatus + '''

exec sp_executesql @sql, N'@p_OfferStatus VARCHAR(100)', @p_OfferStatus = @p_OfferStatus
when I run this in the data tab, it works fine, returning data, but when I try to preview it it tells me there are syntax errors. Anyone know the correct way to use multi selects with stored procs?

View 4 Replies View Related

Stored Proc Not Working, HELP PLEASE!

May 9, 2005

I'm pretty new when it comes to Stored Procs, and for some reason, the CurAge isn't coming up with an actual numeric value. Does anyone see what I am doing wrong?

CREATE PROCEDURE sp_GetTargetProducts
@hmid int,
@wtid int
AS
DECLARE @CurAge INT
if exists(
SELECT LastName, FirstName, HMID, DATEDIFF (YY , BirthDate, GetDate()) As CurAge
FROM Members
WHERE hmid = @hmid
)
BEGIN
SELECT DISTINCT Product, ProductAdvance, AgeBottom, AgeTop, ProductName, ProductDesc, ProductPrice, ProductPicture
FROM Products
WHERE wtid = @wtid
AND AgeBottom <= @CurAge
AND AgeTop >= @CurAge
GROUP BY Product, ProductAdvance, AgeBottom, AgeTop, ProductName, ProductDesc, ProductPrice, ProductPicture
return(1)
END
else
return(0)
GO

View 6 Replies View Related

Update Stored Proc Not Working

Jan 12, 2005

I'm trying to run a UPDATE stored proc to allow my users to update records that are in a datagrid. What the update proc looks like is as follows:

Proc sp_UpdateRecords
@fname nvarchar(30), @lname nvarchar(30), @address1 nvarchar(50), @address2 nvarchar(50), @CITY nvarchar(33), @ST nvarchar(10), @ZIP_OUT nvarchar(5), @ZIP4_OUT nvarchar(4), @home_phone nvarchar(22), @autonumber int
AS
UPDATE NCOA20040603 SET fname=@fname, lname=@lname, address1=@address1, address2=@address2, CITY=@CITY, ST=@ST, ZIP_OUT=@ZIP_OUT, ZIP4_OUT=@ZIP4_OUT, home_phone=@home_phone
WHERE autonumber=@autonumber

The message I'm getting is as follows:

Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index


What could be the problem

Any ideas are appriciated -- Thanks in advance
RB

View 5 Replies View Related

Passing Boolean To Stored Proc As SQLDBtype.bit Not Working

Mar 17, 2004

Hi I was hoping that someone might be able to help me with this.

I'm trying to figure out why my VB.net code below generates 0 or 1 but doesn't insert it when I can execute my stored procedure with: exec sp 0

myParm = myCommand.Parameters.Add("@bolProMembCSNM", SqlDbType.Bit)
myParm.Value = IIf(CBool(rblProMembCSNM.SelectedItem.Value) = True, 1, 0)

I've tried everything I used to use with Classic ASP and am stumped now.
Any ideas? I will have to do this for numerous controls on my pages.

Thanks in advance for any advice.

View 4 Replies View Related

Calling Stored Proc With Default Params From .NET Not Working.

Mar 20, 2006

All,
I have the following :
ALTER PROCEDURE [dbo].[sp_FindNameJon]

@NameName varchar(50)='',
@NameAddress varchar(50)='',
@NameCity varchar(50)='',
@NameState varchar(2)='',
@NameZip varchar(15)='',
@NamePhone varchar(25)='',
@NameTypeId int=0,
@BureauId int,
@Page int=1,
@Count int=100000
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @SqlString nvarchar(3000),@SelectClause nvarchar(1000), @FromClause nvarchar(1000),@WhereClause nvarchar(1000)
DECLARE @ParentSqlString nvarchar(4000)
DECLARE @Start int, @End int
INSERT into aaJonTemp values (@Page, 'here2', @NameCity);
 
And inside of aaJonTemp, I have the following :




NULL
here2
NULL

NULL
here2
NULL
 
How is this possible?  If @Page or @NameCity is NULL, how come it doesn't default to a value in the stored proc?
 
Thx
jonpfl

View 1 Replies View Related

Stored Proc To Assign Variable From Subquery Not Working -- Ugh

Jul 20, 2005

Hi, I'm trying to run a stored proc:ALTER PROCEDURE dbo.UpdateXmlWF(@varWO varchar(50))ASDECLARE @varCust VARCHAR(50)SELECT @varCust=(SELECT Customer FROM tblWorkOrdersWHERE WorkOrder=@varWO)When I remove the SELECT @varCust= I get the correct return. With itin, it just appears to run but nothing comes up in the output window.PLEASE tell me where I'm going wrong. I'm using MSDE, although I don'tthink that should matter?Thanks, Kathy

View 2 Replies View Related

SQL Stored Procedure Not Returning Expected Records.

Oct 24, 2006

I am running a SP using this code:

set ANSI_NULLS ON

set QUOTED_IDENTIFIER ON

GO

ALTER PROCEDURE [dbo].[SelectQueryAddressPostCodeSearchOnly]

(

@postcode nvarchar(50)

)

AS

SET NOCOUNT ON;

SELECT

Cust_Address.Cust_Address_ID,

Cust_Address.Cust_Address_1,

Cust_Address.Cust_Address_2,

Cust_Address.Cust_Address_Post_Code,

Cust_Address.Cust_Post_Town,

Post_Town.Post_Town_ID,

Post_Town.Post_Town_Name,

Post_Town.Post_Town_Priority

FROM Cust_Address

INNER JOIN Post_Town ON Cust_Address.Cust_Post_Town = Post_Town.Post_Town_ID

WHERE Cust_Address.Cust_Post_Town LIKE @postcode



The value for @postcode being passed for testing is "%SA%". I would expect this to return all records which have "SA" in the Post Code field. In the test database I am using there are several (Mainly SA43 0EZ). However the SP in fact returns no matching records at all.



Am I not understanding something here, or is there something to do with space in post code field that is causing a problem ? I have other SPs that are behaving just fine.



Cheers Matt



View 1 Replies View Related

Stored Proc - Get All Records

Jun 30, 2005

I need to understand this a bit more and how to get all records out of the sp.For instance,  SELECT @Name = objName        FROM   Structure  WHERE  Id = @IdI need this to return all the records, not just the last one as it seems to be doing.Do I need to adjust the code behind or the statement above?Thanks,Zath

View 3 Replies View Related

Exec SQL Task: Capture Return Code Of Stored Proc Not Working

May 19, 2006

I am just trying to capture the return code from a stored proc as follows and if I get a 1 I want the SQL Task to follow a failure(red) constrainst workflow and send a SMTP mail task warning the customer. How do I achieve the Exec SQL Task portion of this, i get a strange error message [Execute SQL Task] Error: There is an invalid number of result bindings returned for the ResultSetType: "ResultSetType_SingleRow".



Using OLEDB connection, I utilize SQL: EXEC ? = dbo.CheckCatLog

EXEC SQL Task Editer settings:
RESULTSET: Single Row
PARAMETER MAPPING: User::giBatchID
DIRECTION: OUTPUT
DATATYPE: LONG
PARAMETER NAME: 0

PS-Not sure if I need my variable giBatchID which is an INT32 but I thought it is a good idea to feed the output into here just in case there is no way that the EXEC SQL TASK can chose the failure constrainst workflow if I get a 1 returned or success constraint workflow if I get a 0 returned from stored proceedure





CREATE PROCEDURE CheckCatLog
@OutSuccess INT
AS

-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON
DECLARE @RowCountCAT INT
DECLARE @RowCountLOG INT

---these totals should match
SELECT @RowCountCAT = (SELECT Count(*) FROM mydb_Staging.dbo.S_CAT)
SELECT @RowCountLOG = (SELECT Count(*) FROM mydb_Staging.dbo.S_LOG)
--PRINT @RowCountCAT
--PRINT @RowCountLOG
BEGIN
IF @RowCountCAT <> @RowCountLOG
--PRINT 'Volume of jobs from the CAT file does not match volume of jobs from the LOG file'
--RETURN 1
SET @OutSuccess = 1
END
GO

Thanks in advance

Dave

View 6 Replies View Related

SQLdatasource Wired To A Stored Procedure Not Returning Records.

Dec 9, 2005

Hi, and thanks in advance.
I have VWD 2005 Express and SQL 2005 Express running.
I have a SqlDastasource wired to the stored procedure. When I only include one Control parameter I get results from my Stored procedure, when I inclube both Control Parameters I get no results. I manually remove the second control parameter from the sqldatasource by deleting...
<asp:ControlParameter ControlID="ddlSClosed" DefaultValue="" Name="SClosed" PropertyName="SelectedValue" Type="String" />
I have one Radio Group and one dropdownlist box that supplies the parameters. The dropdownlist parameter is Null or "" when the page is first loaded.
Below is my SQLDatasource and Stored procedure. I am new to Stored Procedures, so be gentle.
Any help would be appreciated!
 
 
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Data for DatabaseSQLConnectionString %>"
ProviderName="<%$ ConnectionStrings:Data for DatabaseSQLConnectionString.ProviderName %>"
SelectCommand="spDisplayServiceOrders" SelectCommandType="StoredProcedure" OnSelecting="SqlDataSource1_Selecting" EnableCaching="True" cacheduration="300" OnSelected="SqlDataSource1_Selected">
<SelectParameters>
<asp:ControlParameter ControlID="RadioButtonList1" ConvertEmptyStringToNull="False"
DefaultValue="2005-11-1" Name="SDate_Entered" PropertyName="SelectedValue" />
<asp:ControlParameter ControlID="ddlSClosed" DefaultValue="" Name="SClosed" PropertyName="SelectedValue" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
 
 
ALTER PROCEDURE [dbo].[spDisplayServiceOrders]
(
@SDate_Entered SmallDateTime,
@SClosed nvarchar(50)= NULL
)
AS
If @SClosed IS NULL
BEGIN

SELECT Service_Orders.SStore_Assigned_Number, Store_Info.Store_Other, Service_Orders.PO_Number, Service_Orders.SWorkType, Service_Orders.Service_Order_Number, Service_Orders.SDate_Entered, Service_Orders.SContact, Service_Orders.SClosed FROM Service_Orders INNER JOIN Store_Info ON Service_Orders.Store_ID = Store_Info.Store_ID
and SDate_Entered >= @SDate_Entered
Order by SDate_Entered DESC
END
ELSE
BEGIN

SELECT Service_Orders.SStore_Assigned_Number, Store_Info.Store_Other, Service_Orders.PO_Number, Service_Orders.SWorkType, Service_Orders.Service_Order_Number, Service_Orders.SDate_Entered, Service_Orders.SContact, Service_Orders.SClosed FROM Service_Orders INNER JOIN Store_Info ON Service_Orders.Store_ID = Store_Info.Store_ID
and SDate_Entered >= @SDate_Entered
and SClosed = @SClosed
Order by SDate_Entered DESC

END

View 2 Replies View Related

UPDATE Stored Proc -- Updated Over All Of My Records

Jan 31, 2005

I wrote a stored proc to be implemented in a datagrid. I went and used it on a record to update some information and it updated THE WHOLE DATABASE WITH THAT ONE RECORD..

IF anyone could shead some light on what I'm doing wrong that would be great.

Here is the syntax for my stored proc.



CREATE PROC updateResults2
@id int, @address1 nvarchar (50), @address2 nvarchar (50), @CITY nvarchar (33), @ST nvarchar (10), @ZIP_OUT nvarchar (5), @ZIP4_OUT nvarchar (4), @home_phone nvarchar (22), @NEWPhone nvarchar (20)
AS
UPDATE Results
SET address1 = @address1,
address2 = @address2,
CITY = @CITY,
ST = @ST,
ZIP_OUT = @ZIP_OUT,
ZIP4_OUT = @ZIP4_OUT,
home_phone = @home_phone,
NEWPhone = @NEWPhone


GO



As said previously it ran but it updated the WHOLE DATABASE with the same change (WHICH I DIDNT WANT IT TO DO)!!

Thanks in advance.
RB

View 3 Replies View Related

Deleting All Records From Table W/stored Proc

Jan 27, 2006

Is there a way to delete records from table passing parameter as tablename? I won't to delete all records from a table dependent on table selected. i'm trying to do this with stored procedure...Table to delete depends on the checkbox selected.

Current code(works)
Public Function DelAll()
MZKDB = MZKHRFin
If sloption = "L" Then
sqlConn.ConnectionString = "Server=" & MZKSrv & ";Initial Catalog=" & MZKDB & ";Integrated Security=SSPI;"
ElseIf sloption = "S" Then
sqlConn.ConnectionString = "Server=" & MZKSrv & ";User id=sa;Password=" & MZKPswd & "; Initial Catalog=" & MZKDB & ";"
End If
sqlConn.Open()
sqlTrans = sqlConn.BeginTransaction()
sqlCmd.Connection = sqlConn
sqlCmd.Transaction = sqlTrans
Try
sqlCmd.CommandText = sqlStr
sqlCmd.ExecuteNonQuery()
sqlTrans.Commit()
frm2.txtResult.Text = frm2.txtResult.Text & " " & TableName & " Prior records have been deleted from the database." & vbCrLf
SetCursor()
Catch e As Exception
Try
sqlTrans.Rollback()
Catch ex As SqlException
If Not sqlTrans.Connection Is Nothing Then
frm2.txtResult.Text = frm2.txtResult.Text & " " & TableName & " An exception of type " & ex.GetType().ToString() & " was encountered while attempting to roll back the transaction." & vbCrLf
SetCursor()
End If
End Try
frm2.txtResult.Text = frm2.txtResult.Text & " " & TableName & " Records were NOT deleted from the database." & vbCrLf
SetCursor()
Finally
sqlConn.Close()
End Try
ResetID()
End Function
If cbGenFY.Checked Then
sqlStr = "DELETE FROM FIN_FiscalYear"
TableName = "dbo.FIN_FiscalYear"
DelAll()
ClearCounts()
timeStepStart = Date.Now
GenFY()
timeStepStop = Date.Now

DispOneCounts()
End If
If cbGenFund.Checked Then
sqlStr = "DELETE FROM FIN_Fund"
TableName = "dbo.FIN_Fund"
DelAll()
ClearCounts()
timeStepStart = Date.Now
GenFund()
timeStepStop = Date.Now
DispOneCounts()
End If
If cbGenFunc.Checked Then
sqlStr = "DELETE FROM FIN_Function"
TableName = "dbo.FIN_Function"
DelAll()
ClearCounts()
timeStepStart = Date.Now
GenFunc()
timeStepStop = Date.Now
DispOneCounts()

End If
If cbGenObject.Checked Then
sqlStr = "DELETE FROM FIN_Object"
TableName = "dbo.FIN_Object"
DelAll()
ClearCounts()
timeStepStart = Date.Now
GenObject()
timeStepStop = Date.Now
DispOneCounts()
End If
If cbGenCenter.Checked Then
sqlStr = "DELETE FROM FIN_Center"
TableName = "dbo.FIN_Center"
DelAll()
ClearCounts()
timeStepStart = Date.Now
GenCenter()
timeStepStop = Date.Now
DispOneCounts()
End If
If cbGenProject.Checked Then
sqlStr = "DELETE FROM FIN_CodeBook"
TableName = "dbo.FIN_CodeBook"
DelAll()
sqlStr = "DELETE FROM FIN_BudgetAccnt"
TableName = "dbo.FIN_BudgetAccnt"
DelAll()
sqlStr = "DELETE FROM FIN_Budget"
TableName = "dbo.FIN_Budget"
DelAll()
sqlStr = "DELETE FROM FIN_Project"
TableName = "dbo.FIN_Project"
DelAll()
ClearCounts()
timeStepStart = Date.Now
GenProject()
timeStepStop = Date.Now
TableName = "dbo.FIN_Project"
DispOneCounts()
End If
If cbGenProgram.Checked Then
sqlStr = "DELETE FROM FIN_Program"
TableName = "dbo.FIN_Program"
DelAll()
ClearCounts()
timeStepStart = Date.Now
GenProgram()
timeStepStop = Date.Now
DispOneCounts()
End If
If cbGenGL.Checked Then
sqlStr = "DELETE FROM FIN_gl"
TableName = "FIN_gl"
DelAll()
ClearCounts()
timeStepStart = Date.Now
GenGL()
timeStepStop = Date.Now
DispOneCounts()
End If
If cbGenRevenue.Checked Then
sqlStr = "DELETE FROM FIN_Revenue"
TableName = "FIN_Revenue"
DelAll()
ClearCounts()
timeStepStart = Date.Now
GenRevenue()
timeStepStop = Date.Now
DispOneCounts()
End If
If cbGenBank.Checked Then
sqlStr = "DELETE FROM FIN_VendorBankAccnt"
TableName = "dbo.FIN_VendorBankAccnt"
DelAll()
sqlStr = "DELETE FROM FIN_VendorBank"
TableName = "dbo.FIN_VendorBank"
DelAll()
sqlStr = "DELETE FROM FIN_bankAdd"
TableName = "dbo.FIN_bankAdd"
DelAll()
sqlStr = "DELETE FROM FIN_bankTERMS"
TableName = "dbo.FIN_bankTerms"
DelAll()
sqlStr = "DELETE FROM FIN_bank"
TableName = "dbo.FIN_bank"
DelAll()
ClearCounts()
timeStepStart = Date.Now
GenBank()
timeStepStop = Date.Now
TableName2 = "dbo.FIN_bankTERMS"
TableName3 = "dbo.FIN_BankAdd"
TableName4 = "dbo.FIN_VendorBank"
TableName5 = "dbo.FIN_VendorBankAccnt"
DispTwoCounts()
End If
If cbFinAP.Checked Then
sqlStr = "DELETE FROM FIN_Period"
TableName = "FIN_Period"
DelAll()
ClearCounts()
timeStepStart = Date.Now
GenPeriod()
timeStepStop = Date.Now
DispOneCounts()
End If

If cbFinVM.Checked Then
sqlStr = "DELETE FROM FIN_vendorClass"
TableName = "FIN_vendorClass"
DelAll()
sqlStr = "DELETE FROM FIN_vendorAdd"
TableName = "FIN_vendorAdd"
DelAll()
sqlStr = "DELETE FROM FIN_vendor"
TableName = "FIN_vendor"
DelAll()
sqlStr = "DELETE FROM FIN_AddressType"
TableName = "FIN_AddressType"
DelAll()
sqlStr = "DELETE FROM FIN_VendorStatus"
TableName = "FIN_VendorStatus"
DelAll()
sqlStr = "DELETE FROM States"
TableName = "States"
DelAll()
sqlStr = "DELETE FROM Country"
TableName = "Country"
sqlStr = "DELETE FROM FIN_IndustrialCodes"
TableName = "FIN_IndustrialCodes"
DelAll()
ClearCounts()
timeStepStart = Date.Now
GenIndCodes()
timeStepStop = Date.Now
DispOneCounts()
DelAll()
ClearCounts()
timeStepStart = Date.Now
FinVendStat()
timeStepStop = Date.Now
TableName = "FIN_VendorStatus"
DispOneCounts()
ClearCounts()
timeStepStart = Date.Now
FinAddrType()
timeStepStop = Date.Now
TableName = "FIN_AddressType"
DispOneCounts()
ClearCounts()
timeStepStart = Date.Now
GenCountry()
timeStepStop = Date.Now
TableName = "Country"
DispOneCounts()
ClearCounts()
timeStepStart = Date.Now
GenState()
timeStepStop = Date.Now
TableName = "States"
DispOneCounts()
ClearCounts()
timeStepStart = Date.Now
FinVM()
timeStepStop = Date.Now
TableName = "FIN_Vendor"
TableName2 = "FIN_VendorAdd"
DispTwoCounts()
End If
If cbFinbudget.Checked Then
sqlStr = "DELETE FROM FIN_BudgetAccnt"
TableName = "FIN_BudgetAccnt"
DelAll()
sqlStr = "DELETE FROM FIN_Budget"
TableName = "FIN_Budget"
DelAll()
sqlStr = "DELETE FROM FIN_CodeBook"
TableName = "FIN_CodeBook"
DelAll()
ClearCounts()
TableName = "FIN_Budget"
timeStepStart = Date.Now
FinBudget()
timeStepStop = Date.Now
DispOneCounts()
ClearCounts()
TableName = "FIN_Codebook"
TableName2 = "FIN_budgetAccnt"
timeStepStart = Date.Now
FinCodeBook()
timeStepStop = Date.Now
DispTwoCounts()
ClearCounts()
End If

View 4 Replies View Related

Showing Records Where Count(*) Is Zero (in A Stored Proc)

Jul 20, 2005

This seems so easy....change the join to show all records, but thezero records still do not showI want to join 2 tables....basically Customers and Orders....get thetotal number of orders for each Customer within a date range...but Ican't seem to show records where the total for a particular Customeris zero (which is very important info)There must be an easy way???thanks,Paul

View 2 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

Integration Services :: Commit N Number Of Records (SSIS Versus Stored Procedure)

May 8, 2015

I have a stored proc that is returning the results I need for output to .txt file.

Is there a way in SSIS to commit 50K (or whatever number) row batches at a time or should I just handle this in the stored proc?

select * into #TempTable
from SomeTable
[WHILE LOOP] --throttle commit batches of 50K rowcount
select *
from #TempTable
[END LOOP]
drop table #TempTable

But If I'm doing this in SSIS, I can't drop the #temp table otherwise I have nothing to output right?

View 6 Replies View Related

Can You Trace Into A Stored Proc? Also Does RAISERROR Terminate The Stored Proc Execution.

Feb 13, 2008

I am working with a large application and am trying to track down a bug. I believe an error that occurs in the stored procedure isbubbling back up to the application and is causing the application not to run. Don't ask why, but we do not have some of the sourcecode that was used to build the application, so I am not able to trace into the code.
So basically I want to examine the stored procedure. If I run the stored procedure through Query Analyzer, I get the following error message:
Msg 2758, Level 16, State 1, Procedure GetPortalSettings, Line 74RAISERROR could not locate entry for error 60002 in sysmessages.
(1 row(s) affected)
(1 row(s) affected)
I don't know if the error message is sufficient enough to cause the application from not running? Does anyone know? If the RAISERROR occursmdiway through the stored procedure, does the stored procedure terminate execution?
Also, Is there a way to trace into a stored procedure through Query Analyzer?
-------------------------------------------As a side note, below is a small portion of my stored proc where the error is being raised:
SELECT  @PortalPermissionValue = isnull(max(PermissionValue),0)FROM Permission, PermissionType, #GroupsWHERE Permission.ResourceId = @PortalIdAND  Permission.PartyId = #Groups.PartyIdAND Permission.PermissionTypeId = PermissionType.PermissionTypeId
IF @PortalPermissionValue = 0BEGIN RAISERROR (60002, 16, 1) return -3END 
 

View 3 Replies View Related







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