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


ADVERTISEMENT

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

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

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

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, 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 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

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

Data Binding To A Stored Procedure That Returns Two Result Sets

Mar 6, 2007

Hi there everyone.  I have a stored procedure called “PagingTableâ€? that I use for performing searches and specifying how many results to show per ‘page’ and which page I want to see.  This allows me to do my paging on the server-side (the database tier) and only the results that actually get shown on the webpage fly across from my database server to my web server.  The code might look something like this:
 
strSQL = "EXECUTE PagingTable " & _
"@ItemsPerPage = 10, " & _
"@CurrentPage = " & CStr(intCurrentPage) & ", " & _
"@TableName = 'Products', " & _
"@UniqueColumn = 'ItemNumber', " & _
"@Columns = 'ItemNumber, Description, ListPrice, QtyOnHand', " & _
"@WhereClause = '" & strSQLWhere & "'"
 
The problem is the stored procedure actually returns two result sets.  The first result set contains information regarding the total number of results founds, the number of pages and the current page.  The second result set contains the data to be shown (the columns specified).  In ‘classic’ ASP I did this like this.
 
'Open the recordset
rsItems.Open strSQL, conn, 0, 1
 
'Get the values required for drawing the paging table
intCurrentPage = rsItems.Fields("CurrentPage").Value
intTotalPages = rsItems.Fields("TotalPages").Value
intTotalRows = rsItems.Fields("TotalRows").Value
 
'Advance to the next recordset
Set rsItems = rsItems.NextRecordset
 
I am trying to do this now in ASP.NET 2.0 using the datasource control and the repeater control.  Any idea how I can accomplish two things:
 
A) Bind the repeater control to the second resultset
B) Build a “pager� of some sort using the values from the first resultset

View 3 Replies View Related

Problem In Executing Stored Procedure With Temp Table Returns Result Sets

Mar 23, 2006

Hi,
we are facing problem in executing a stored procedure from Java Session Bean,

coding is below.

pst = con.prepareStatement("EXEC testProcedure ?", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
pst.setString(1, "IN");
//
rs = pst.executeQuery();
rs.last();
System.out.println(" Row Number "+rs.getRow());
rs.beforeFirst();
while(rs.next())
{
System.out.println(" Procedure is "+rs.getString(1));
}

same sp working perfectly with SQL Server 2000

am getting a error message

com.microsoft.sqlserver.jdbc.SQLServer
Exception: A server cursor cannot be opened on the given statement or statements
. Use a default result set or client cursor.



If a SP doesnt have a temp table, then there is no issue, SP executes perfectly, but if a SP has a temp table, this error occurs.

SP :

create proc testProcedure
@countrCode varchar(3)
as

select countryname INTO #TMPCOU from country where countryCode = @countrCode
SELECT COUNTRYNAME FROM #TMPCOU

Its really very urgent. Please help me...!

Rgds,

Venkatesh.

View 2 Replies View Related

Java Code To Retrieve Data From Stored Procedure Which Returns Cursor Varying Output?

May 11, 2015

java code to retrieve the data returned by SQL server stored procedure which is of CURSOR VARYING OUTPUT type and display the details on console.

View 3 Replies View Related

Problem With Getting Last Record From Stored Procedure

Mar 27, 2008

I have three tables in this shipping scenario -- one to record the Sender's Info, one to record the Recipient's Info, and one to record the Shipment Info, and I perform the inserts in that order.  I want to get the last inserted USERID (which is an INT, and the PK) from both the Sender's table and the Recipient's table so that I can record that info as a foreign key in my Shipment table. 
Everything compiles and runs.  However, every time I run it, "2" is inserted in my foreign key columns in the Shipment Info table.  I can't figure out where that 2 is coming from.
So I analyzed the SP in query analyzer, and when I run it it shows:
"(0 row(s) returned)@RETURN_VALUE=0"
Can anyone help me with this?  I'm so close I think:
First, my SP's:
***********************************************************
ALTER PROCEDURE dbo.INSERT_NEW_SENDER(@firstname nvarchar(50), @lastname nvarchar(50), @email nvarchar(50),@phone nvarchar(50))ASBEGIN TRANSACTIONDECLARE @NewID intSET NOCOUNT ONINSERT INTO SHP_USER(email, firstname, lastname, phone) VALUES(@email, @firstname, @lastname, @phone)SET @NewID = CONVERT(int, SCOPE_IDENTITY())COMMIT TRANSACTIONGO
**************************************************************
ALTER PROCEDURE dbo.SP_INSERT_NEW_RECIPIENT(@firstname nvarchar(50),@lastname nvarchar(50),@company nvarchar(50),@division nvarchar(50),@address1 nvarchar(50),@address2 nvarchar(50),@city nvarchar (50),@state nvarchar (50),@zip nvarchar (50),@country nvarchar(50),@phone nvarchar(50),@fax nvarchar(50),@email nvarchar(50),@address_type nvarchar(50),@recipient_type nvarchar(50),@NewID int OUTPUT)AS/* SET NOCOUNT ON */ INSERT INTO SHP_recipient(firstname, lastname, company, division, address1, address2, city, state, zip, country, phone, fax, email, address_type, recipient_type) VALUES(@firstname, @lastname, @company, @division, @address1, @address2, @city, @state, @zip, @country, @phone, @fax, @email, @address_type, @recipient_type)SET @NewID = CONVERT(int, SCOPE_IDENTITY())RETURN
**********************************************************************
And my .NET stuff:
//NEW USER INSERT SqlCommand myCommand;
SqlDataReader myReader; int sender_userid = 0;
int recipient_userid = 0;
//int NewID; myCommand = new SqlCommand("INSERT_NEW_SENDER", conn);
myCommand.CommandType = CommandType.StoredProcedure;myCommand.Parameters.Add(new SqlParameter("@firstname", str_firstname));
myCommand.Parameters.Add(new SqlParameter("@lastname", str_lastname));myCommand.Parameters.Add(new SqlParameter("@phone", str_phone));
myCommand.Parameters.Add(new SqlParameter("@email", str_email));myCommand.Parameters.Add(new SqlParameter("@NewID", ParameterDirection.Output));myCommand.UpdatedRowSource = UpdateRowSource.OutputParameters;
myCommand.Connection.Open();
myReader = myCommand.ExecuteReader();sender_userid = (int)myCommand.Parameters["@NewID"].Value;
myCommand.Connection.Close();
//RECIPIENT INSERT SqlCommand myCommand2;
SqlDataReader myReader2; myCommand2 = new SqlCommand("SP_INSERT_NEW_RECIPIENT", conn);
myCommand2.CommandType = CommandType.StoredProcedure;
//myCommand2.Parameters.Add(new SqlParameter("@userid", recipient_userid));myCommand2.Parameters.Add(new SqlParameter("@firstname", str_recip_firstname));
myCommand2.Parameters.Add(new SqlParameter("@lastname", str_recip_lastname));myCommand2.Parameters.Add(new SqlParameter("@company", str_company));
myCommand2.Parameters.Add(new SqlParameter("@division", str_division));myCommand2.Parameters.Add(new SqlParameter("@address1", str_recip_addr1));
myCommand2.Parameters.Add(new SqlParameter("@address2", str_recip_addr2));myCommand2.Parameters.Add(new SqlParameter("@city", str_city));
myCommand2.Parameters.Add(new SqlParameter("@state", str_state));myCommand2.Parameters.Add(new SqlParameter("@zip", str_zip));
myCommand2.Parameters.Add(new SqlParameter("@country", str_country));myCommand2.Parameters.Add(new SqlParameter("@phone", str_recip_phone));
myCommand2.Parameters.Add(new SqlParameter("@fax", str_fax));myCommand2.Parameters.Add(new SqlParameter("@email", str_recip_email));
myCommand2.Parameters.Add(new SqlParameter("@recipient_type", str_recipient_type));myCommand2.Parameters.Add(new SqlParameter("@address_type", str_Address_Type));
myCommand2.Parameters.Add(new SqlParameter("@NewID", ParameterDirection.Output));myCommand2.UpdatedRowSource = UpdateRowSource.OutputParameters;
myCommand2.Connection.Open();
myReader2 = myCommand2.ExecuteReader();recipient_userid = (int)myCommand2.Parameters["@NewID"].Value;
myCommand2.Connection.Close();
try
{
conn.Open();
//INSERT data into the SHP_SHIPMENTS tableSqlCommand cmd = new SqlCommand("INSERT INTO SHP_SHIPMENTS(sender, recipient, ship_method, rma, payment_method, must_pay, project, business_unity, office, attachments, shipment_description,shipment_notes,date_created) VALUES(@sender_userid, @recipient_userid, @ship_method,@rma,@payment_method,@must_pay,@project,@business_unity,@office,@attachments,@shipment_description,@shipment_notes, GetDate())", conn);
 cmd.Parameters.Add(new SqlParameter("@sender_userid", sender_userid));
cmd.Parameters.Add(new SqlParameter("@recipient_userid", recipient_userid));cmd.Parameters.Add(new SqlParameter("@ship_method", str_ship_method));
cmd.Parameters.Add(new SqlParameter("@rma", str_rma));cmd.Parameters.Add(new SqlParameter("@payment_method", str_payment_method));
cmd.Parameters.Add(new SqlParameter("@must_pay", str_must_pay));cmd.Parameters.Add(new SqlParameter("@project", str_project));
cmd.Parameters.Add(new SqlParameter("@business_unity", str_business_unit));cmd.Parameters.Add(new SqlParameter("@office", str_office));
cmd.Parameters.Add(new SqlParameter("@attachments", str_attachments));cmd.Parameters.Add(new SqlParameter("@shipment_description", str_shipment_description));cmd.Parameters.Add(new SqlParameter("@shipment_notes", str_shipment_notes));
cmd.ExecuteNonQuery();
 
}catch (Exception ex)
{FormMessage.Text = "Error: Insert Shipment - " + ex.Message;
}
finally
{
conn.Close();
}
 
 
 
 
 

View 34 Replies View Related

Using A Stored Procedure To Insert A New Record

Apr 7, 2004

ok I have a stored procedure......
I pass in the variables that are requried....What is the best way to add a record
using my stored procedure in VB.net code in a button click event......
How might i do this with a data reader,,data adapter.....OR What.......................Do I need to declare all my varaibles I am adding to this new record in the line after POSCODE or can vb.net do this without a parameter statemetn




CREATE procedure dbo.Appt_AddAppt
(
@ClinicID int,
@AccountNum nvarchar(10),
@DOS nvarchar(12),
@POSCODE nvarchar(5)
)
as
Insert into Clinic_Appointments (ClinicID,AcctNumber,DateOfService,PlaceOfService,PlaceOfServiceID)
Values (@ClinicID,@AccountNum,@DOS,@POSCODE,@ClinicID)



GO

View 4 Replies View Related

Stored Procedure To Insert Record

Jul 27, 2004

I have an SP to add a record to the database but i get the error shown below. Any help appreciated.

Stored Procedure:

CREATE PROCEDURE addUser
@username char(15),
@password char(12)

AS
INSERT INTO users(username, password) VALUES (@username, @password)

GO


Code calling SP:

Dim myConnection As New System.Data.SqlClient.SqlConnection(ConnectionString)

Dim cmd As New SqlCommand("addUser", myConnection)
MyDataAdapter = New SqlDataAdapter()
'MyDataAdapter = New SqlDataAdapter("addUser", myConnection)

With cmd 'MyDataAdapter
.CommandType = CommandType.StoredProcedure
.Parameters.Add("@username", SqlDbType.Char).Value = username
.Parameters.Add("@password", SqlDbType.Char).Value = password
End With

Try
myConnection.Open()
cmd.ExecuteNonQuery()
Catch ex As SqlException
Finally
myConnection.Close()
End Try


I get an error message on the line: cmd.ExecuteNonQuery()

System.FormatException: Input string was not in a correct format.

View 2 Replies View Related

How Do I Loop Through A Record Set In A Stored Procedure?

Jan 17, 2006

Below is a stored procedure that designed to populate a drop down menu system on a website. It works fine as long as the 'id's in the first select start at 1 and are sequential. It fails to grab all the sub tables if the ids are not sequential. So, how do I structure the loop so that the WHERE clause uses not the loop iterator, but rather, the ids from the first Select statement.
Alternatively, is there a more elgant approach that will return the same set of recordsets?
Any help would be much appreciatedThanks
ALTER PROCEDURE dbo.OPA_GetMenuItemsASDeclare @i tinyint ,@tc tinyintSet @i = 1
/* Select for top level menu items*/
SELECT id, label, url, sortFROM mainNavORDER BY sort
Set @tc = @@rowcount
while @i <= @tc
beginSet @i = (@i + 1)
/* Select for submenu itemsSELECT id, label, url, sort, mainNavIdFROM SubNavWHERE (mainNavId = @i)ORDER BY mainNavId, sortend
RETURN
 
 

View 7 Replies View Related

How Do I Loop Thru A Record Set In A Stored Procedure?

Jan 17, 2006

Below is a stored procedure that designed to populate a drop down menu system on a website. It works fine as long as the 'id's in the first select start at 1 and are sequential. It fails to grab all the sub tables if the ids are not sequential. So, how do I structure the loop so that the WHERE clause uses not the loop iterator, but rather, the ids from the first Select statement.

Alternatively, is there a more elgant approach that will return the same set of recordsets?

Any help would be much appreciated
Thanks

ALTER PROCEDURE dbo.OPA_GetMenuItems
AS
Declare @i tinyint ,
@tc tinyint
Set @i = 1

/* Select for top level menu items*/

SELECT id, label, url, sort
FROM mainNav
ORDER BY sort

Set @tc = @@rowcount

while @i <= @tc

begin
Set @i = (@i + 1)

/* Select for submenu items*/
SELECT id, label, url, sort, mainNavId
FROM SubNav
WHERE (mainNavId = @i)
ORDER BY mainNavId, sort
end

RETURN

View 6 Replies View Related

Duplicate Record Inserted With Stored Procedure

Feb 4, 2008

I'm calling the stored procedure below to insert a record but every record is inserted into my table twice. I can't figure out why. I'm using Sql Server 2000.  Thanks.CREATE PROCEDURE sp_AddUserLog(@Username varchar(100),@IP varchar(50))AS SET NOCOUNT ONINSERT INTO TUserLogs (Username, IP) VALUES (@Username, @IP)GO  Sub AddUserLog(ByVal Username As String)
Dim SqlText As String
Dim cmd As SqlCommand
Dim strIPAddress As String

'Get the users IP address
strIPAddress = Request.UserHostAddress

Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString)
SqlText = "sp_AddUserLog"
cmd = New SqlCommand(SqlText)
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = con

cmd.Parameters.Add("@Username", SqlDbType.VarChar, 100).Value = Username
cmd.Parameters.Add("@IP", SqlDbType.VarChar, 100).Value = strIPAddress

Try
con.Open()
cmd.ExecuteNonQuery()
Finally
con.Close()
End Try

End Sub 

View 7 Replies View Related

Help Getting An ID, Back From A Record, That Has Just Been Inserted With A Stored Procedure

Mar 21, 2008

Hi,
I was wondering if anyone could offer me some advice. I am currently using a stored procedure to insert records into a database. I want to be able to retrieve the ID (primar key) from the item that has just been inserted using the stored procedure. The ID I want to get back is Meter_ID
This is my stored procedure:ALTER PROCEDURE dbo.quote
 
(@Business_Name nvarchar(50),
@Business_Type nvarchar(50),@Contact_Title nchar(10),
@Contact_First_Name nvarchar(50),@Contact_Last_Name nvarchar(50),
@Address_Line_1 nvarchar(MAX),@Address_Line_2 nvarchar(MAX),
@City nvarchar(MAX),@Postcode nchar(7),
@Tel_No nchar(11),@E_mail_Address nvarchar(50),
@Distributor_ID int,@Profile_Class int,
@Meter_Time_Code int,@Line_Loss_Factor int,
@Unique_Identifier1 int,@Unique_Identifier2 int,
@Check_Digit int,@Tariff nchar(20),
@UnitRate1AnnualUsage nchar(10),@UnitRate2AnnualUsage nchar(10),
@UnitRate1SubTotal money,@UnitRate2SubTotal money,
@QuoteTotal money
)
ASINSERT INTO client_details (Business_Name, Business_Type, Contact_Title, Contact_First_Name, Contact_Last_Name, Address_Line_1, Address_Line_2, City, Postcode, Tel_No, email_Address)VALUES (@Business_Name, @Business_Type,@Contact_Title, @Contact_First_Name, @Contact_Last_Name, @Address_Line_1, @Address_Line_2, @City, @Postcode, @Tel_No, @E_mail_Address)
 
DECLARE @Client_ID INTSET @Client_ID = scope_identity()
 INSERT INTO meter_quote (Client_ID, Tariff, Meter_Distributor_ID, Meter_Profile_Class, Meter_Time_Code, Meter_Line_Loss_Factor, Unique_Identifier1, Unique_Identifier2, Check_Digit, UnitRate1AnnualUsage, UnitRate2AnnualUsage, UnitRate1SubTotal, UnitRate2SubTotal, QuoteTotal)VALUES (@Client_ID, @Tariff, @Distributor_ID, @Profile_Class, @Meter_Time_Code, @Line_Loss_Factor, @Unique_Identifier1, @Unique_Identifier2, @Check_Digit, @UnitRate1AnnualUsage, @UnitRate2AnnualUsage, @UnitRate1SubTotal, @UnitRate2SubTotal, @QuoteTotal)
 
RETURN
And this is the code I have in my asp page:<asp:SqlDataSource ID="SqlDataSource3" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
InsertCommand="quote" InsertCommandType="StoredProcedure">
<InsertParameters><asp:ControlParameter ControlID="TextBoxBusinessName" DefaultValue=""
Name="Business_Name" PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="DropDownBusinessType" Name="Business_Type"
PropertyName="SelectedValue" Type="String" /><asp:ControlParameter ControlID="DropDownListTitle" Name="Contact_Title"
PropertyName="SelectedValue" Type="String" /><asp:ControlParameter ControlID="TextBoxFirstName" Name="Contact_First_Name"
PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="TextBoxLastName" Name="Contact_Last_Name"
PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="TextBoxAddressLine1" Name="Address_Line_1"
PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="TextBoxAddressLine2" Name="Address_Line_2"
PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="TextBoxAddressLine3" Name="City"
PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="TextBoxPostcode" Name="Postcode"
PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="TextBoxTelNo" Name="Tel_No"
PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="TextBoxEmail" Name="E_mail_Address"
PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="TextBoxDistributorID" Name="Distributor_ID"
PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="TextBoxProfileClass" Name="Profile_Class"
PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="TextBoxMeterTimeCode" Name="Meter_Time_Code"
PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="TextBoxLineLossFactor" Name="Line_Loss_Factor"
PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="TextBoxUniqueIdentifier1" Name="Unique_Identifier1"
PropertyName="Text" Type="String" /> <asp:ControlParameter ControlID="TextBoxUniqueIdentifier2" Name="Unique_Identifier2"
PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="TextBoxCheckDigit" Name="Check_Digit"
PropertyName="Text" Type="String" /> <asp:ControlParameter ControlID="LabelTariff2" Name="Tariff"
PropertyName="Text" Type="String" /> <asp:ControlParameter ControlID="TextBoxUnitRate1Usage" Name="UnitRate1AnnualUsage"
PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="LabelUnitRate2Usage" Name="UnitRate2AnnualUsage"
PropertyName="Text" Type="String" /><asp:ControlParameter ControlID="LabelUnitRate1Total" Name="UnitRate1SubTotal"
PropertyName="Text" Type="Decimal" /><asp:ControlParameter ControlID="LabelUnitRate2Total" Name="UnitRate2SubTotal"
PropertyName="Text" Type="Decimal" /><asp:ControlParameter ControlID="LabelQuoteTotal" Name="QuoteTotal"
PropertyName="Text" Type="Decimal" />
</InsertParameters>
</asp:SqlDataSource>
And the following in the C# code:
try
{
SqlDataSource3.Insert();//Insert quote details into the database using a stored procedure
}catch (Exception ex)
{LabelInsertException.Text = "Failed" + ex.Message;
}
Any help would be much appreciated
Thanks, Hayley
 
 

View 6 Replies View Related

Inserting A Record Using Values From Another Stored Procedure

Aug 2, 2006

Hello, I'm trying to accomplish 3 things with one stored procedure.I'm trying to search for a record in table X, use the outcome of thatsearch to insert another record in table Y and then exec another storedprocedure and use the outcome of that stored procedure to update therecord in table Y.I have this stored procedure (stA)CREATE PROCEDURE procstA (@SSNum varchar(9) = NULL)ASSET NOCOUNT ONSELECT OType, Status, SSN, FName, LNameFROM CustomersWHERE (OType = 'D') AND (Status = 'Completed') AND (SSN = @SSNum)GO.Then, I need to create a new record in another table (Y) using the SSN,FName and Lname fields from this stored procedure.After doing so, I need to run the second stored procedure (stB) Here itis:CREATE PROCEDURE procstB( @SSNum varchar(9) = NULL)ASSET NOCOUNT ON-- select the recordSELECT OrderID, OrderDate, SSNFROM OrdersGROUP BY OrderID, OrderDate, SSNHAVING (ProductType = 'VVSS') AND (MIN(SSN) = @SSNum)GO.After running this, I need to update the record I created a moment agoin table Y with the OrderDate and OrderID from the second storedprocedure.Do you guys think that it can be done within a single stored procedure?Like for example, at the end of store procedure A creating an insertstatement for the new record, and then placing something like execprocstB 'SSN value'? to run stored procedure B and then having aupdate statement to update that new record?Thanks for all your help.

View 1 Replies View Related

Stored Procedure For Deleting A Record With Contstraints (m:n)

Oct 9, 2007

I can not get this stored procedure to delete my records...

I have a
contact table
RecordID
FirstName
LastName
etc

and a Address table

RecordID
Street
Zip
Town
Country

And a Relation table

RecordID
ContactID
AddressID
CreateDate


set ANSI_NULLS ON

set QUOTED_IDENTIFIER ON

GO

ALTER PROCEDURE [dbo].[bc_Contact_Delete]

@ContactID int

AS

--SET NOCOUNT ON

BEGIN TRY

BEGIN TRANSACTION -- Start the transaction



-- Delete all Adresses

DELETE FROM [Address]

WHERE

RecordId in (SELECT ca.AdressId from [ContactAddress] ca

where

ca.ContactID = @ContactID)

-- Delete all Relations

DELETE FROM [ContactAdress]



WHERE ContactID = @ContactID

--- Delete Kontakt

DELETE FROM [Contact] WHERE (([RecordId] = @ContactID))

COMMIT TRANSACTION

END TRY

BEGIN CATCH

-- Whoops, there was an error

ROLLBACK TRANSACTION

-- Raise an error with the

-- details of the exception

DECLARE @ErrMsg nvarchar(4000),

@ErrSeverity int

SELECT @ErrMsg = ERROR_MESSAGE(),

@ErrSeverity = ERROR_SEVERITY()



RAISERROR(@ErrMsg, @ErrSeverity, 1)

END CATCH

RETURN


My Errormessage is

The DELETE statement conflicted with the REFERENCE constraint "FK_bc_ContactAdress_bc_Address". The conflict occurred in database "bContacts", table "dbo.ContactAddress", column 'AdressID'.

Can someone please post me an advice?

View 5 Replies View Related

Error When Attempting To Insert Record Using Stored Procedure

Jun 21, 2006

I am trying to save user data to a sql table but keep getting the following error;
Unable to cast object of type 'System.Boolean' to type 'System.Data.SqlClient.SqlParameter'.
I am using VWD Express Edition with .NET 2.0 and a SQL 2000 database. The code that generates the error is as follows;
Public Function chkUser(ByVal strUser As String) As Stringdim MyConnection As SqlConnectionDim MyCommand As SqlCommandDim ReturnString As StringDim params As SqlParameterDim SelectCmd As String = "wm_CheckUser"MyConnection = New SqlConnection(myConnectionString)MyCommand = New SqlCommand(SelectCmd, MyConnection)MyCommand.CommandType = CommandType.StoredProcedure
Tryparams = MyCommand.Parameters.Add("@parUser", SqlDbType.VarChar, 100).Value = strUserMyCommand.Connection.Open()MyCommand.ExecuteNonQuery()ReturnString = "Record Exists!"Catch Exp As SqlExceptionReturnString = ReturnError(Exp.Number, "Users", Exp.Message)End TryMyCommand.Connection.Close()Return ReturnString
End Function
Basically, I'm traying to check to see if a user id already exists in the database before saving the data the user entered. If the email address entered by the user is already in the database I want a message to be shown to the user. If the email address does not exist then the data entered by the user is saved and the form goes to step two (2) of the user registration process.
Any help with this would be greately appreciated. I can't seem to see what is wrong here. Please someone help.
Thanks,
Jaime

View 7 Replies View Related







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