Calling A Stored Procedure, Returns Empty

Nov 30, 2005

hi, im new to this site so i don't know if i'm posting in the correct forum. anyway, this is my code:---Dim dbMac As DBLibrary = Nothing

dbMac = New DBLibrary(General.GetMACConnectionString)dbMac.OpenConnection("SPR_STAFFMAIN_GETEMPLOYEERECORDS")dbMac.CreateParameter("@USERENTITYID", GetUserEntityID(), Data.SqlDbType.Int)drpEmpNumbers.DataSource = dbMac.GetDataView("StaffMaintenance")gridStaffMaintenance.DataSource = dbMac.GetDataView("StaffMaintenance")gridStaffMaintenance.DataBind()---DBLibrary is a class that opens a connection to the SQL server. i'm getting an empty grid even though the stored procedure returns a row when i test it in the analyzer. is there to debug or test this code? thanks!

View 1 Replies


ADVERTISEMENT

Calling SQL 2005 Stored Procedure That Returns A Value

Apr 14, 2007

I have a stored procedure on a SQL server, which is workign correctly to check some date/time parameters and then insert a row into a log table.
I am calling it from an ASP page.   Initially I just called it and didn't worry about the return value.  However the Stored procedure now will return a value to determine if it made the change or not and if not why (ie log entry was at incorrect time etc).
 I woudl liek to capture this returned value in my code to display a message to the user but am havign problems finding the right way to get the value.
I am calling the SP as follows:
     Shared Sub createlogentry(ByVal ID, ByVal tme, ByVal val)        Dim result As String        Dim cs As String = ConfigurationManager.ConnectionStrings("connecttion1").ToString        Using con As New System.Data.SqlClient.SqlConnection(cs)            con.Open()            Dim cmd As New System.Data.SqlClient.SqlCommand()            cmd.Connection = con            cmd.CommandType = Data.CommandType.StoredProcedure            cmd.CommandText = "CreateLogEntry"            cmd.Parameters.Add("@ChID", Data.SqlDbType.Int)            cmd.Parameters("@ChID").Value = ID            cmd.Parameters.Add("@Value", Data.SqlDbType.Int)            cmd.Parameters("@Value").Value = val            result = cmd.ExecuteNonQuery().ToString        End Using    End Sub
 
I have tried amending the ExecuteNonQuery line to ExecuteReader()
 Any help appreciated
Regards
Clive

View 3 Replies View Related

Calling A Stored Procedure That Does An Insert And Returns One Value

Feb 3, 2004

Hi !

I have trying to do an insert with a subroutine that calls a stored procedure, but it doesn’ t run. The page loads properly but nothing is inserted in the table of the database, no errors appears after submit the form.
<asp:Button id="SubmitButton" OnClick="Send_data" Text="Submit" runat="server"/>

Here is the code:


Sub Send_data(Sender As Object, E As EventArgs)

Dim CmdInsert As New SqlCommand("new_user1", strConnection)
CmdInsert.CommandType = CommandType.StoredProcedure

Dim InsertForm As New SqlDataAdapter()
InsertForm.InsertCommand = CmdInsert

CmdInsert.Parameters.Add(New SqlParameter("@RETURN_VALUE", SqlDbType.bigint, 8, "User_id"))
CmdInsert.Parameters("@RETURN_VALUE").Direction = ParameterDirection.ReturnValue

CmdInsert.Parameters.Add(New SqlParameter("@e_mail", SqlDbType.varchar, 50, "e_mail"))
CmdInsert.Parameters("@e_mail").Value = mail.Text()

End Sub


What it lacks?

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

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

Stored Procedure Returns No Value

Mar 1, 2006

Hi,I have a stored procedure (the code is below) that I use to retrieveone value from my database. I tested the code in Query Analyzer, and itworks (I get the value I was looking for). However, when I call thesame code from the stored procedure, I get no value. The code that isexecuted is the same and the input parameter is the same. Does anybodyhave an idea?The code:SELECT Top 1CharID,CharName,CategoryName,CharDescription,UserIDFROM [Character]WHERE CharName='Character'-- returns the right valueThe Stored Procedure:CREATE PROCEDURE SpCharacters_SelectOneByUserName@UserName NVarCharASSELECT Top 1CharID,CharName,CategoryName,CharDescription,UserIDFROM CharacterWHERE CharName=@UserNameGO-- returns no value

View 2 Replies View Related

(Could Not Find Stored Procedure ''.) When Calling A User Defined Procedure

Feb 4, 2008

Hi,I'm tring to call a stored procedure i'v made from a DNN module, via .net control.When I try to execute this sql statement: EXEC my_proc_name 'prm_1', 'prm_2', ... the system displays this error: Could not find stored procedure ''. (including the trailings [".] chars :)I've tried to run the EXEC statement from SqlServerManagement Studio, and seems to works fine, but sometimes it displays the same error. So i've added the dbname and dbowner as prefix to my procedure name in the exec statement and then in SqlSrv ManStudio ALWAYS works, but in dnn it NEVER worked... Why? I think it could be a db permission problem but i'm not able to fix this trouble, since i'm not a db specialist and i don't know which contraint could give this problem. Also i've set to the ASPNET user the execute permissions for my procedure... nothing changes :( Shoud someone could help me? Note that I'm using a SqlDataSource object running the statement with the select() method (and by setting the appropriate SelectCommandType = SqlDataSourceCommandType.StoredProcedure ) and I'm using the 2005 sql server express Thank in advance,(/d    

View 3 Replies View Related

Stored Procedure Returns -1 For A Bit Field

Apr 15, 2008

Hello,I have a stored procedure: -- Get an individual league match by IDALTER PROCEDURE [dbo].[mb_League_GetLeagueMatchByID](   @LeagueMatchID  int)ASSET NOCOUNT ONSELECT * FROM mb_LeagueMatch WHERE mb_LeagueMatch.LeagueMatchID = @LeagueMatchIDThe mb_LeagueMatch table has a column named IsActive that is a bit datatype.The value for all rows is set to true (in database explorer in visual studio 2005).When I execute the above stored procedure I always get -1 (I'm guessing that means null) as a result for IsActive if it was true and 0 when false (as expected).However, when I run a query on the database for the same parameter, I get the expected 1 as the value for IsActive.Has anyone seen this before?Thanks,Howard

View 4 Replies View Related

Stored Procedure Returns Boolean???

Sep 30, 2004

hi,
i just want to check whether the given data exists in the database. i am using stored procedure. is there any way to know whether that value exists in database without the need to select anything?

View 1 Replies View Related

Is It Possible To Have A Stored Procedure That Returns 2 Values?

Oct 5, 2004

Is It possible to have a stored procedure that returns 2 values?
and call it from a C# webforms application.
Thanks.

View 7 Replies View Related

LIKE In Stored Procedure Returns No Record

Jun 29, 2005

I have following stored procedure:
-------------
CREATE PROCEDURE dbo.Test
@name as char(36)

as

select a, b
from testtable
where name LIKE @name +'%'
------------

when I run the select statement from query analyzer,

select a, b from testtable where name LIKE 'a%'

it returns records.

But when I call the stored procedure from query analyzer,

exec Test 'a'

it returns no record.

What might be wrong?

Any help is appreciated.

View 3 Replies View Related

How Many Records A Stored Procedure Returns?

Oct 11, 2007

Hi,
I need to know whether a stored procedure returns only a single record or it can return more than one if the query if for example to return all records in a specific date range.
Thanks.

View 6 Replies View Related

SQL Stored Procedure Returns Duplicates

Mar 23, 2007

I am new to SQL and SQL Server world. There must be a simple solutionto this, but I'm not seeing it. I am trying to create a crystalreport (v8.5) using a stored procedure from SQL Server (v2000) inorder to report from two databases and to enable parameters.When I create the stored procedure, it joins multiple one-to-manyrelationship tables. This results in repeated/duplicate records. Isthis an issue that should be solved within the stored procedure, or isthis inevitable? If latter, how do you eliminate the duplicates inCrystal Reports?Let's say we have three different tables - Event, Food, Equipment.Each event may have multiple food and multiple equipments; some eventsmay not have food and/or equipments. The stored procedure outcome maylook like this:Event Food Food_Qty EquipmentEquipment_QtyEvent1 Food2 10 Equipment51Event1 Food4 10NULL NULLEvent2 Food4 50 Equipment210Event2 Food4 50 Equipment52Event2 Food1 12 Equipment210Event2 Food1 12 Equipment52As you can see in Event2, for each Food variations, Equipment valuesrepeat. When I am creating a Crystal Reports, I have the duplicationproblem.What I would like to see in the report is either:Event1Food2, 10 Equipment5, 1Food4, 10Event2Food4, 50 Equipment2, 10Food1, 12 Equipment5, 2OR:Event1Food2, 10Food4, 10Equipment5, 1Event2Food4, 50Food1, 12Equipment2, 10Equipment5, 2Attempt1: Using "Eliminate Duplicate Record" option does not work withthe Equipment section since CR does not recognize "Equipment2" in thethird line of the table and "Equipment2" in the fifth line of thetable as duplicates.Event1 Food2, 10 Equipment5, 1Food4, 10Event2 Food4, 50 Equipment2, 10Equipment5, 2Food1, 12 Equipment2, 10(duplication)Equipment5, 2(duplication)Attempt2: I created group for each category (Event, Food, Equipment),put the data in Group Headers and used "Suppress Section" to eliminateif the same equipments are listed more than once within the Foodgroup. This eliminated the duplication, but the items do not aligncorrectly.Event1 Food2, 10 Equipment5, 1Food4, 10Event2 Food4, 50 Equipment2, 10Equipment5, 2Food1, 12 (I want this to appear right below the'Food4, 50' line)I would really appreciate any suggestions! Thank you in advance.

View 4 Replies View Related

Stored Procedure Returns Duplicates

Apr 10, 2007

I am trying to create a report in Crystal Reports (v 8.5). I have astored procedure to pull data from two databases and parameters.There are multiple one-to-many relationships and the stored procedurereturns duplicates; e.g., one schedule may have multiple resources,supplies, and/or orders (and one order may have multiple foods). Isthere a way to stop the duplication?The stored procedure looks like this:************************************************** **********************************SET QUOTED_IDENTIFIER OFFGOSET ANSI_NULLS OFFGOCREATE PROCEDURE usp_rpt1 (@start_date smalldatetime,@end_date smalldatetime,@rpt_type varchar(3),@rpt_id int)ASset nocount on--Set up some string variables to build the selection query for theparameters supplieddeclare @fields varchar(255)declare @tables varchar(255)declare @where varchar(2000)CREATE TABLE #tmp_sched(sched_id int, rpt_type_desc varchar(100),rpt_id int)set end_date = midnight of next daySELECT @end_date = DATEADD(day,1,@end_date)SELECT @end_date = CONVERT(smalldatetime,CONVERT(varchar(4),YEAR(@end_date)) + '-'+CONVERT(varchar(2),MONTH(@end_date)) + '-'+CONVERT(varchar(2),DAY(@end_date))IF @rpt_type = 'LOC'INSERT INTO #tmp_schedSELECT DISTINCT s.sched_id, l.loc_desc, l.loc_idFROM tbl_sched sLEFT JOIN tbl_sched_res_date srd ON s.sched_id = srd.sched_idLEFT JOIN tbl_res r ON srd.res_id = r.res_idLEFT JOIN tbl_grp g ON r.grp_id = g.grp_idLEFT JOIN tbl_loc l ON g.loc_id = l.loc_idWHERE l.loc_id = CONVERT(varchar(12),@rpt_id)AND g.obsolete_flag = 0AND r.obsolete_flag = 0ANd l.obsolete_flag = 0AND s.deleted_flag = 0AND srd.mtg_start_date_local >=CONVERT(varchar(20), @start_date, 1)AND srd.mtg_start_date_local <CONVERT(varchar(20), @end_date+1,1)IF @rpt_type = 'GRP'INSERT INTO #tmp_schedSELECT DISTINCT s.sched_id, g.grp_desc, g.grp_idFROM tbl_sched sLEFT JOIN tbl_sched_res_date srd ON s.sched_id =srd.sched_idLEFT JOIN tbl_res r ON srd.res_id = r.res_idLEFT JOIN tbl_grp g ON r.grp_id = g.grp_idWHERE (g.grp_id = CONVERT(varchar(12),@rpt_id)OR g.parent_grp_id =CONVERT(varchar(12),@rpt_id))AND g.obsolete_flag = 0AND r.obsolete_flag = 0AND s.deleted_flag = 0AND srd.mtg_start_date_local >=CONVERT(varchar(20), @start_date, 1)AND srd.mtg_start_date_local <CONVERT(varchar(20), @end_date+1,1)IF @rpt_type = 'RES'INSERT INTO #tmp_schedSELECT DISTINCT s.sched_id, r.res_desc, r.res_idFROM tbl_sched sLEFT JOIN tbl_sched_res_date srd ON s.sched_id =srd.sched_idLEFT JOIN tbl_res r ON srd.res_id = r.res_idWHERE r.res_id = CONVERT(varchar(12),@rpt_id)AND r.obsolete_flag = 0AND s.deleted_flag = 0AND srd.mtg_start_date_local >=CONVERT(varchar(20), @start_date, 1)AND srd.mtg_start_date_local <CONVERT(varchar(20), @end_date+1, 1)IF @rpt_type = 'REG'INSERT INTO #tmp_schedSELECT DISTINCT s.sched_id, reg.region_desc,reg.region_idFROM tbl_sched sLEFT JOIN tbl_sched_res_date srd ON s.sched_id =srd.sched_idLEFT JOIN tbl_res r ON srd.res_id = r.res_idLEFT JOIN tbl_grp g ON r.grp_id = g.grp_idLEFT JOIN tbl_loc l ON g.loc_id = l.loc_idLEFT JOIN tbl_region reg ON l.loc_id = reg.region_idWHERE reg.region_id = CONVERT(varchar(12),@rpt_id)AND reg.obsolete_flag = 0AND l.obsolete_flag = 0AND g.obsolete_flag = 0AND r.obsolete_flag = 0AND s.deleted_flag = 0AND srd.mtg_start_date_local >=CONVERT(varchar(20), @start_date, 1)AND srd.mtg_start_date_local <CONVERT(varchar(20), @end_date+1, 1)IF @rpt_type NOT IN ('LOC','GRP','RES','REG')INSERT INTO #tmp_schedSELECT DISTINCT s.sched_id, g.grp_desc, g.grp_idFROM tbl_sched sLEFT JOIN tbl_sched_res_date srd ON s.sched_id =srd.sched_idLEFT JOIN tbl_res r ON srd.res_id = r.res_idLEFT JOIN tbl_grp g ON r.grp_id = g.grp_idWHERE (g.grp_id = 0 OR g.parent_grp_id = 0)AND g.obsolete_flag = 0AND r.obsolete_flag = 0AND s.deleted_flag = 0AND srd.mtg_start_date_local >=CONVERT(varchar(20), @start_date, 1)AND srd.mtg_start_date_local <CONVERT(varchar(20), @end_date+1,1)--This is the selection for our reportSELECT Description = ts.rpt_type_desc,Date = CONVERT(varchar(12),srd.mtg_start_date_local,101), StartTime = srd.mtg_start_date_local,EndTime = srd.mtg_end_date_local,SchedID = s.sched_id,MeetingTitle = s.sched_desc,ResourceUsed = r.res_desc,ResourceSetup = su.setup_desc + ' (' +CONVERT(varchar(10),rs.capacity) + ')',NumberOfAttendees = Attendees.string_value,OrderID = ord.order_id,FoodQty = CONVERT (int,oi.order_qty),FoodDesc = i.item_name,Side = sidei.item_name,MeetingDesc = ord.order_desc,Supplies = suppliesudf.udf_desc,SuppliesVal = supplies.value,AccountCode = ord.order_user_acct_code,host.string_value as MeetingHost,CateringNotes = ord.order_notes,FoodNotes = oi.order_notesFROM #tmp_sched tsJOIN tbl_sched s ON ts.sched_id = s.sched_idJOIN tbl_sched_res_date srd ON ts.sched_id = srd.sched_idJOIN tbl_res r ON srd.res_id = r.res_idJOIN tbl_sched_res_setup srs ON s.sched_id = srs.sched_id andr.res_id = srs.res_idLEFT JOIN tbl_res_setup rs ON srs.setup_id = rs.setup_id ANDsrs.res_id = rs.res_idLEFT JOIN tbl_setup su ON rs.setup_id = su.setup_idLEFT JOIN tbl_sched_request_tab_val supplies ON s.sched_id =supplies.sched_idAND ((supplies.request_tab_id =(SELECT request_tab_id FROM tbl_request_tab WHERE(request_tab_hdr = 'A) Meeting Supplies')))OR (supplies.request_tab_id =(SELECT request_tab_id FROM tbl_request_tab WHERE(request_tab_hdr = 'Mtg Supplies-PEMC'))))AND (CONVERT(varchar, supplies.value) NOT IN ('0', ''))LEFT JOIN tbl_udf suppliesudf ON supplies.udf_id =suppliesudf.udf_idJOIN tbl_sched_udf_val attendees ON attendees.sched_id = s.sched_idAND attendees.udf_id =(SELECT udf_id FROM tbl_udf WHERE udf_desc = 'Number ofAttendees') --UDF For No of AttendeesJOIN tbl_sched_udf_val host ON host.sched_id = s.sched_idAND host.udf_id =(SELECT udf_id FROM tbl_udf WHERE udf_desc = 'MeetingHost') --UDF For meeting host nameLEFT JOIN RSCatering.dbo.tbl_Order ord ON ord.order_sched_id =s.sched_id --Our link to table in other databaseJOIN RSCatering.dbo.tbl_order_item oi ON ord.order_id =oi.order_idLEFT JOIN RSCatering.dbo.tbl_menu_item mi ON oi.menu_item_id =mi.menu_item_idLEFT JOIN RSCatering.dbo.tbl_item i ON mi.item_id = i.item_idLEFT JOIN RSCatering.dbo.tbl_order_item_sides side ONoi.order_item_id = side.order_item_idLEFT JOIN RSCatering.dbo.tbl_item sidei ON side.item_id =sidei.item_idWHERE ord.deleted_flag = 0 AND oi.deleted_flag = 0ORDER BYts.rpt_type_desc,srd.mtg_start_date_local,srd.mtg_ end_date_local,r.res_descDROP TABLE #tmp_schedGOSET QUOTED_IDENTIFIER OFFGOSET ANSI_NULLS ONGO************************************************** ****************************************The simplified result looks like:Sched2 Resource1 Supply1 Order5Sched2 Resource1 Supply1 Order6Sched2 Resource1 Supply3 Order5Sched2 Resource1 Supply3 Order6Sched2 Resource2 Supply1 Order5Sched2 Resource2 Supply1 Order6Sched2 Resource2 Supply3 Order5Sched2 Resource2 Supply3 Order6However, I want the result to look like:Sched2 Resource1 Supply1 Order5Sched2 Resource2 Supply3 Order6Any suggestion is greatly appreciated.

View 6 Replies View Related

Stored Procedure Returns Different Data When You Run It In T-SQL

Dec 13, 2007

I have a stored procedure




Code Block
CREATE PROCEDURE WEA_SelectEmployeeListByCourseOrProject
@ProjectID int,
@CourseID int,
@blnIsSearch int,
@strUserName nvarchar(20)

AS
SET CONCAT_NULL_YIELDS_NULL OFF

DECLARE @strRole nvarchar(15),
@ContactID int
SELECT @strRole = Role, @ContactID = ContactID FROM Contact WHERE UserName = @strUserName
Select DISTINCT Contact.ContactID ID, UPPER(Surname + 'gd ' + Forename ) AS Description, UPPER(Surname + ' ' + Forename + ' ' + ContactReference) AS Description_CR
, UPPER(ISNULL(ContactReference,'')) ContactReference
FROM Contact
LEFT JOIN AssignedEmployee on Contact.ContactID = AssignedEmployee.ContactID
WHERE RUEmployee=1
AND
( ((@CourseID = 0 AND @blnIsSearch=1 ) OR COALESCE(AssignedEmployee.CourseID,0) = @CourseID))
AND
(@ProjectID = 0 OR COALESCE(AssignedEmployee.ProjectID,0) = @ProjectID)
AND
(
(@strRole = 'MIS_TUTOR' AND
(AssignedEmployee.ContactID = @ContactID
OR CourseID IN (SELECT CourseID FROM AssignedEmployee WHERE ContactID = @ContactID AND Lead = 1)
OR AssignedEmployee.ProjectID IN (SELECT ProjectID FROM AssignedEmployee WHERE CourseID IS NULL AND Lead = 1 AND ContactID = @ContactID))
)
OR
(@strRole <> 'MIS_TUTOR')
)
SET CONCAT_NULL_YIELDS_NULL ON
GO






now if i run this stored procedure in Query Analyzer like so...

exec wea_SelectEmployeeListByCourseOrProject 0,0,1,'K_T'

i get 48 records returned.

but if i lift the SQL out of the stored procedure and run it in Query Analyzer like so....





Code Block
SET CONCAT_NULL_YIELDS_NULL OFF

DECLARE @ProjectID int,
@CourseID int,
@blnIsSearch int,
@strUserName nvarchar(20)
SET @ProjectID = 0
SET @CourseID = 0
SET @blnIsSearch = 1
SET @strUserName = 'K_T'


DECLARE @Role nvarchar(15),
@ContactID int
SELECT @Role = Role, @ContactID = ContactID FROM Contact WHERE UserName = @strUserName
PRINT @ContactID
Select DISTINCT Contact.ContactID ID, UPPER(Surname + ' ' + Forename ) AS Description, UPPER(Surname + ' ' + Forename + ' ' + ContactReference) AS Description_CR
, UPPER(ISNULL(ContactReference,'')) ContactReference
FROM Contact
LEFT JOIN AssignedEmployee on Contact.ContactID = AssignedEmployee.ContactID
WHERE RUEmployee=1
AND
( ((@CourseID = 0 AND @blnIsSearch=1 ) OR COALESCE(AssignedEmployee.CourseID,0) = @CourseID)) -- the above line was modified to make sure only employees explicitly assigned to a project are brought back. unless it's a search
AND
(@ProjectID = 0 OR COALESCE(AssignedEmployee.ProjectID,0) = @ProjectID)
AND
(
(@Role = 'MIS_TUTOR'
AND ( (AssignedEmployee.ContactID = @ContactID OR CourseID IN (SELECT CourseID FROM AssignedEmployee WHERE ContactID = @ContactID AND Lead = 1)))
OR
AssignedEmployee.ProjectID IN (SELECT ProjectID FROM AssignedEmployee WHERE CourseID IS NULL AND Lead = 1 AND ContactID = @ContactID)
)
OR
(@Role <> 'MIS_TUTOR')
)


SET CONCAT_NULL_YIELDS_NULL ON







i only get 5 records returned???

so why do i get a difference when its the same SQL??

Username 'K_T' is of role 'MIS_TUTOR' therefore @Role = 'MIS_TUTOR'

any help on unravelling this mystery is appreciated!

Cheers,
Craig

View 5 Replies View Related

OLE DB Command And Stored Procedure That Returns Value And/or Error

May 23, 2006

Guys,

could someone please tell me : am I supposed to use the OLE DB
Command in a dataflow to call a stored procedure to return a value? Or
is it just supposed to be used to call a straightforward insert
statement only?



What I am hoping to do:



I have a table with a few columns and one identity column. In a
dataflow I would like to effect an insert of a record to this table and
retrieve the identity value of the inserted record... and I'd like to
store the returned identity in a user variable.



If I AM supposed to be able to do this... then how on earth do I do it?

I have spent hours fooling around with the OLE DB command trying to call a stored proc and get a return value.



In the Advanced Editor any time I try to add an output column (by
clicking on Add Column) I just get an error dialog that says "the
component does not allow adding columns to this input or output)



So, am getting pretty concussed .. banging my head of the wall like this...

So put me out of my misery someone please.... is the OLE DB Command intended for this or not?



Thanks

PJ

View 4 Replies View Related

Stored Procedure That Returns The Next Value In Sequence For A Column

Mar 9, 2008

I have a Column called SaleID in some tables in a Database.The SaleID column has the int datatype. I need a stored procedure that returns the next value in sequence for the SaleID column.

For Example,
If the last value inserted into the SaleID column was 1022 the stored procedure should return 1023
If the last value inserted into the SaleID column was 1023 the stored procedure should return 1024.
If the last value inserted into the SaleID column was 1024 the stored procedure should return 1025.

Also an exclusive lock should be maintained while the the stored procedure is running.

I am using SQL Server 2005.

View 4 Replies View Related

Empty Parameters Into A Stored Procedure

Sep 13, 2006

Greetings! This is my first ever post here, so please be gentle.

I have a stored procedure that will be accepting many parameters (around 10). Any number of them can be empty (empty with a length of zero, but probably not Null per se).

How do I do a Select... Where... where if the parameter is empty it ignores it in the 'Where' but if the parameter had anything in it, it becomes part of the filter?

Thanks!

View 5 Replies View Related

Variable Always Empty In Stored Procedure

Jul 20, 2005

In the code below, the statement 'Print @Sites' prints nothing, eventhough the cursor contains 4 records, and 'Print @Site' prints theappropriate values. Can anyone see my mistake? I am attempting toprint a delimited string of the values referred to by @Sites.Thanks.Dan FishermanDECLARE SiteCursor CURSORGLOBALSCROLLSTATICFOR SELECT OfficeName FROM ClientOffices WHERE ClientID=12 ORDER BYOfficeNameOPEN SiteCursorDECLARE @Sites varchar(1000)DECLARE @Site varchar(100)FETCH NEXT FROM SiteCursor INTO @SiteWHILE @@FETCH_STATUS=0BEGINprint @SiteSET @Sites = @Sites + ', ' + @SiteFETCH NEXT FROM SiteCursor INTO @SiteENDPRINT @SitesCLOSE SiteCursorDEALLOCATE SiteCursorGO

View 4 Replies View Related

Can Anyone Tell Me Why This Returns An Empty Value?

Feb 26, 2007

@Names is a query string passed in, I need to count the number of records as a  result of the below query/ 
 
Dim test As String
Dim sqlConnection3 As New SqlConnection("data Source=EQ-520-WEBSQLEXPRESS;Initial Catalog=CRDB.MDF;Integrated Security=True")
Dim cmd As New SqlCommand
 
Dim returnValue As Object
cmd.CommandText = "SELECT COUNT(ReqID) AS Expr1, LineManager FROM TblReqMain GROUP BY LineManager HAVING (LineManager = @Names)"
cmd.CommandType = Data.CommandType.Text
cmd.Connection = sqlConnection3
cmd.Parameters.Add("@Names", Data.SqlDbType.NVarChar)
sqlConnection3.Open()
cmd.Parameters("@Names").Value = test
If test = "" Then
Response.Write("An error occured")
Exit Sub
Else
returnValue = cmd.ExecuteScalar()
sqlConnection3.Close()
Label6.Text = "Number " & returnValue

View 1 Replies View Related

SqlDataSource With Stored Procedure With Parameters Returns No Data

Mar 21, 2007

I have a Gridview bound to a SQLDataSource that uses a Stored Procedure expecting 1 or 2 parameters. The parameters are bound to textbox controls. The SP looks up a person by name, the textboxes are Last Name, First Name. It will handle last name only (ie. pass @ln ='Jones' and @fn=null and you get all the people with last name=Jones. I tested the SP in Management Studio and it works as expected. When I enter a last name in the Last Name textbox and no First Name I get no results. If I enter a Last Name AND First Name I get results. I don't understand.
Here's the HTML View of the page. The only code is to bind the Gridview when the Search button is pressed.
<%@ Page Language="VB" AutoEventWireup="true" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server">    <title>Untitled Page</title></head><body>    <form id="form1" runat="server">        <div>            <asp:TextBox ID="TextBox1" runat="server" TabIndex=1></asp:TextBox>&nbsp;            <asp:TextBox ID="TextBox2" runat="server" TabIndex=2></asp:TextBox>&nbsp;            <asp:Button ID="Button1" runat="server" Text="Search" TabIndex=3  />            &nbsp;&nbsp;            <hr />        </div>        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"    DataSourceID="SqlDataSource1" DataKeyNames="EmpID" CellPadding="4"    EnableSortingAndPagingCallbacks="True" ForeColor="#333333" GridLines="None"    AutoGenerateColumns="False">            <Columns>                <asp:BoundField DataField="EmpID" HeaderText="Emp ID" ReadOnly="True" SortExpression="EmpID" />                <asp:BoundField DataField="FullName" HeaderText="Full Name" SortExpression="FullName" />                <asp:BoundField DataField="Nickname" HeaderText="Nickname" ReadOnly="True" SortExpression="Nickname" />                <asp:BoundField DataField="BGS2" HeaderText="BGS2" SortExpression="BGS2" />                <asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone" />                <asp:BoundField DataField="email" HeaderText="Email" SortExpression="email" />            </Columns>        </asp:GridView>        <asp:SqlDataSource ID="SqlDataSource1" runat="server"    ConnectionString="<%$ ConnectionStrings:EmpbaseConnectionString %>"            SelectCommand="GetByName" SelectCommandType="StoredProcedure">            <SelectParameters>                <asp:ControlParameter ControlID="TextBox2" Name="fn" PropertyName="Text" Type="String"      ConvertEmptyStringToNull=true/>                <asp:ControlParameter ControlID="TextBox1" Name="ln" PropertyName="Text" Type="String"      ConvertEmptyStringToNull=true/>            </SelectParameters>        </asp:SqlDataSource>    </form>   </body></html>

View 7 Replies View Related

Help Getting My If Statement To Reconize That My Stored Procedure Returns DBNULL

Mar 31, 2008

 Ok well i have a stored procedure that returns an integer between 1 and 5. My problem now is i want to check to see if the table will return NULL and if so i don't want to assign the value to my variable otherwise it'll trow an error. My code is listed below but i keep getting the error "Conversion from type 'DBNull' to type 'Integer' is not valid." i've also tried If getoptionpicked.Parameters("@optionpicked").Value = Nothing ThenIf getoptionpicked.Parameters("@optionpicked").Value Is system.dbnull Then below is the rest of the code If getoptionpicked.Parameters("@optionpicked").Value Is Nothing Then        Else            optionpicked = getoptionpicked.Parameters("@optionpicked").Value            If optionpicked = 1 Then                option1.Checked = True            ElseIf optionpicked = 2 Then                option2.Checked = True            ElseIf optionpicked = 3 Then                option3.Checked = True            ElseIf optionpicked = 4 Then                option4.Checked = True            ElseIf optionpicked = 5 Then                option5.Checked = True            Else            End If        End If   

View 1 Replies View Related

How To Speed Up Stored Procedure That Returns 35,000 Plus Rows Of Data?

May 8, 2008

I'm pretty new to .NET and am looking for advice on how to speed up a simple stored procedure that returns 35,000 plus rows.   It's a super simple query that returns a client list.  It's just that there is soooooo many rows, it's super slow when the page loads. 

View 4 Replies View Related

Valid Stored Procedure Returns Error In ASP.net Application

Jan 17, 2005

I have a stored procedure that works when executed in query analyzer. (It is also way too long to post here) When called from my application ado.net returns the error:

Invalid object name #idTable

If I run the proc in query analyzer using the same parameters (copied from quickwatch while debugging) there is no error.

While very complicated, this procedure runs quickly so timing out is not an issue.

Does anyone know why a proc would run in query analyzer and not in an asp.net/c# application?

Thank you.

View 4 Replies View Related

DataRead Of Stored Procedure Returns Column Name Instead Of Null

Jan 6, 2006

I have a stored procedure like "select * from ThisTable"
I'm doing a dataread like:
Dim val as String = dateRead("column_from_ThisTable")
If the value in the column is not null everything works great, but if the value is null, instead of getting a value of "" which I expect, I get the column name??? In this case "column_from_ThisTable"
How do I make sure I get "" returned when the value in the column is db.null?

View 3 Replies View Related

Stored Procedure Returns Unnecessary Conversion Error

Oct 22, 2007

The Query:


Code:

AS
DECLARE@UPLIDCount int
DECLARE @OldUPLIDCount int
SELECT @UPLIDCount = (SELECT Count(UPLID)/1000 AS adjcount
FROM tblProvLicSpecloc
WHERE DelDate is null
OR DelDate > GETDATE())


IF EXISTS(SELECT var FROM tblDMaxVars WHERE var = 'UPLID Count')
BEGIN
SELECT @OldUPLIDCount = (SELECT var FROM tblDMaxVars WHERE var = 'UPLID Count')
IF @UPLIDCount > @OldUPLIDCount
BEGIN
UPDATE tblDMaxVars
SET value = '' + CAST((@UPLIDCount*1000) AS nvarchar(1000)) + ''
WHERE var = 'UPLID Count'
END
END
ELSE
BEGIN
INSERT INTO tblDMaxVars (var, value, description)
VALUES ('UPLID Count', '' + CAST((@UPLIDCount*1000) AS nvarchar(1000)) + '', 'counts UPLID records and rounds down to the nearest thousand')
END


GO



The table tblDMaxVars only has three columns, none of which are integers, yet I still return this error:


Code:

Syntax error converting the varchar value 'UPLID Count' to a column of data type int.



Please help.

View 2 Replies View Related

Calling Stored Procedure Fromanother Stored Procedure

Oct 10, 2006

Hi,I am getting error when I try to call a stored procedure from another. I would appreciate if someone could give some example.My first Stored Procedure has the following input output parameters:ALTER PROCEDURE dbo.FixedCharges @InvoiceNo int,@InvoiceDate smalldatetime,@TotalOut decimal(8,2) outputAS .... I have tried using the following statement to call it from another stored procedure within the same SQLExpress database. It is giving me error near CALL.CALL FixedCharges (@InvoiceNo,@InvoiceDate,@TotalOut )Many thanks in advanceJames

View 16 Replies View Related

Calling A Stored Procedure Or Function From Another Stored Procedure

Mar 2, 2007

Hello people,

When I am trying to call a function I made from a stored procedure of my creation as well I am getting:

Running [dbo].[DeleteSetByTime].

Cannot find either column "dbo" or the user-defined function or aggregate "dbo.TTLValue", or the name is ambiguous.

No rows affected.

(0 row(s) returned)

@RETURN_VALUE =

Finished running [dbo].[DeleteSetByTime].

This is my function:

ALTER FUNCTION dbo.TTLValue

(

)

RETURNS TABLE

AS

RETURN SELECT Settings.TTL FROM Settings WHERE Enabled='true'

This is my stored procedure:

ALTER PROCEDURE dbo.DeleteSetByTime

AS

BEGIN



SET NOCOUNT ON



DECLARE @TTL int

SET @TTL = dbo.TTLValue()



DELETE FROM SetValues WHERE CreatedTime > dateadd(minute, @TTL, CreatedTime)

END

CreatedTime is a datetime column and TTL is an integer column.

I tried calling it by dbo.TTLValue(), dbo.MyDatabase.TTLValue(), [dbo].[MyDatabase].[TTLValue]() and TTLValue(). The last returned an error when saving it "'TTLValue' is not a recognized built-in function name". Can anybody tell me how to call this function from my stored procedure? Also, if anybody knows of a good book or site with tutorials on how to become a pro in T-SQL I will appreciate it.

Your help is much appreciated.

View 6 Replies View Related

Calling A Stored Procedure

Mar 23, 2007

Hi, i've had this query method:
34           public void AddDagVerslagCategorie(int logID, HistoriekDetail historiekDetail)35           {36               SqlConnection oConn = new SqlConnection(_connectionString);37               string strSql = "Insert into LogDetail (LogID, CategorieID, Inhoud)";38               strSql += "values(@logID, @categorieID, @inhoud)";39               SqlCommand oCmd = new SqlCommand(strSql, oConn);40               oCmd.Parameters.Add(new SqlParameter("@logID", SqlDbType.Int)).Value = logID;41               oCmd.Parameters.Add(new SqlParameter("@categorieID", SqlDbType.Int)).Value = historiekDetail.CategorieID;42               oCmd.Parameters.Add(new SqlParameter("@inhoud", SqlDbType.VarChar, 100)).Value = historiekDetail.Inhoud;43   44               try45               {46                   oConn.Open();47                   int rowsAffected = oCmd.ExecuteNonQuery();48                   if (rowsAffected == 0) throw new ApplicationException("Fout toevoegen historiek detail");49                   oCmd.CommandText = "select @@IDENTITY";50                   oCmd.Parameters.Clear();51                   historiekDetail.HistoriekDetailID = (int)(decimal)oCmd.ExecuteScalar();52               }53               catch (Exception ex)54               {55                   throw new ApplicationException("Fout toevoegen historiek detail: " + ex.Message);56               }57               finally58               {59                   if (oConn.State == ConnectionState.Open) oConn.Close();60               }61           }
which i've converted to a stored procedure: 1 ALTER PROCEDURE [dbo].[insert_DagVerslagDetail]
2 -- Add the parameters for the stored procedure here
3 @dagverslagdetailID int,
4 @logID int,
5 @categorieID int,
6 @inhoud varchar(100)
7 AS
8 BEGIN
9 -- SET NOCOUNT ON added to prevent extra result sets from
10 -- interfering with SELECT statements.
11 SET NOCOUNT ON;
12 SET @dagverslagdetailID = SCOPE_IDENTITY()
13
14 -- Insert statements for procedure here
15 BEGIN TRANSACTION
16 INSERT LogDetail (LogID, CategorieID, Inhoud)
17 VALUES(@logID, @categorieID, @inhoud)
18 COMMIT TRANSACTION
19 END
  
 
Now i would like to call that stored procedure in my previous method, so i've changed it to this:
 1 public void AddDagVerslagCategorie(int logID, HistoriekDetail historiekDetail)
2 {
3 SqlConnection oConn = new SqlConnection(_connectionString);
4 string strSql = "insert_DagVerslagDetail";
5 strSql += "values(@logID, @categorieID, @inhoud)";
6 SqlCommand oCmd = new SqlCommand(strSql, oConn);
7 oCmd.CommandType = CommandType.StoredProcedure;
8 oCmd.Parameters.Add(new SqlParameter("@logID", SqlDbType.Int)).Value = logID;
9 oCmd.Parameters.Add(new SqlParameter("@categorieID", SqlDbType.Int)).Value = historiekDetail.CategorieID;
10 oCmd.Parameters.Add(new SqlParameter("@inhoud", SqlDbType.VarChar, 100)).Value = historiekDetail.Inhoud;
11
12 try
13 {
14 oConn.Open();
15 int rowsAffected = oCmd.ExecuteNonQuery();
16 if (rowsAffected == 0) throw new ApplicationException("Fout toevoegen historiek detail");
17 oCmd.CommandText = "select @@IDENTITY";
18 oCmd.Parameters.Clear();
19 historiekDetail.HistoriekDetailID = (int)(decimal)oCmd.ExecuteScalar();
20 }
21 catch (Exception ex)
22 {
23 throw new ApplicationException("Fout toevoegen historiek detail: " + ex.Message);
24 }
25 finally
26 {
27 if (oConn.State == ConnectionState.Open) oConn.Close();
28 }
29 }

 
Do i still need the lines 17                   oCmd.CommandText = "select @@IDENTITY";
                                 19                   historiekDetail.HistoriekDetailID = (int)(decimal)oCmd.ExecuteScalar();
Because i've declared the identity in my stored procedure

View 1 Replies View Related

Out Vs. Ref When Calling Stored Procedure

Apr 8, 2008

Hi, I have a stored procedure, and it is expecting an output. If I declared the passing varaible as ref, it compiles fine, but it is not returning any value. If I pass the varaible as out, and add the paramater
MyComm.Parameters.Add(new SqlParameter("@ReturnValue", returnValue));  it gives the following error. 
Compiler Error Message: CS0269: Use of unassigned out parameter 'quoteID'.
 And if I don't supply the previous statement, the following error occurs.
System.Data.SqlClient.SqlException: Procedure 'CreateData' expects parameter '@ReturnValue', which was not supplied.
How Can I fix this? thanks.

View 2 Replies View Related

Calling A DTS Stored Procedure From ASP.NET

Dec 15, 2003

I have a stored procedure that calls a DTS package to grab a text file that has been uploaded to the server and merge it with a table on the database. The DTS package works woderfully in SQL, as does the the file upload. The problem arrises when I create a stored procedure to run the DTS package. I know that you have to shell out and do a command line on the SQL server (and I think that I got the syntax correct) but its calling the Stored Procedure in the ASP.NET app that is causing me hardship. Here is the code that I have so far:

Stored Procedure:

CREATE PROCEDURE spSampleData AS exec master..xp_cmdshell 'dtsrun /SZEUSsqlServer113 /NdtsPackage /UuserID /Ppassword'
GO


VB to run DTS:

Dim myCommand As SqlCommand
myCommand.CommandType = CommandType.StoredProcedure
myCommand.CommandText = "spSampleData"
myCommand.ExecuteNonQuery()


I'm not sure what I am doing wrong but any help would be great.

Thanks!

View 3 Replies View Related

Calling Stored Procedure

Feb 6, 2004

I am trying to set up a call to a Stored Procedure to do an Insert. Here is my code snippet:

<%@ Page Language="VB" %>
<%@ import Namespace="System" %>
<%@ import Namespace="System.Data.SqlClient" %>
.
.
.
Dim loConn as New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
Dim cmdInsert as New SQLCommand("AdminUser_Insert", loConn)
cmdInsert.CommandType = CommandType.StoredProcedure

Dim InsertForm As New SqlDataAdapter()
InsertForm.InsertCommand = cmdInsert

cmdInsert.Parameters.Add(New SqlParameter("@RETURN_VALUE", SqlDbType.bigint, 8, "Account_Number"))
cmdInsert.Parameters("@RETURN_VALUE").Direction = ParameterDirection.ReturnValue
cmdInsert.Parameters.Add(New SqlParameter("@UserID", SqlDbType.varchar, 50, "UserID"))
cmdInsert.Parameters("@UserID").Value = Request("UserID")
cmdInsert.Parameters.Add(New SqlParameter("@Password", SqlDbType.varchar, 32, "Password"))
cmdInsert.Parameters("@Password").Value = Request("Password")
cmdInsert.Parameters.Add(New SqlParameter("@First_Name", SqlDbType.varchar, 32, "First_Name"))
cmdInsert.Parameters("@First_Name").Value = Request("FirstName")
cmdInsert.Parameters.Add(New SqlParameter("@Middle_Name", SqlDbType.varchar, 32, "Middle_Name"))
cmdInsert.Parameters("@Middle_Name").Value = Request("MiddleName")
cmdInsert.Parameters.Add(New SqlParameter("@Last_Name", SqlDbType.varchar, 32, "Last_Name"))
cmdInsert.Parameters("@Last_Name").Value = Request("LastName")

loConn.Open()
command.ExecuteNonQuery()
loConn.Close()


I get the following error:

Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: BC30451: Name 'CommandType' is not declared.


This error happens on the line: cmdInsert.CommandType = CommandType.StoredProcedure

Any help would be appreciated,
Greg

View 2 Replies View Related

Calling DTS From Stored Procedure

May 22, 2000

Hello everybody,

How can I call DTS from stored procedure, any help pls.

PS: I appreciate if you please give me an example.

Thank you....

View 2 Replies View Related







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