Stored Procedures Subquery Returns More Than One Value?
Nov 13, 2014
SQL (using 2012) .I'm trying to create some stored procedures that calculate stats needed for item response theory and test scoring (things like reliability, correlation, etc.). I'm writing a procedure that's aimed at splitting a test in half (first half of the items and second half of the items) and calculating each individual (TestID) score for each half. I can insert the first half of the test, but end up getting an error stating that the subquery returned more than one value. I know it's being caused by the group by clause, but if I remove it I end up with a total count of the items answered correctly, but it's necessary for me to link it batch to the TestID (so each row should have a BatchID [same for all at the moment], a unique TestId, a corresponding FirstHalfScore and a corresponding SecondHalfScore for each testID).
Insert into SplitHalfTestScores (BatchId, TestID, FirstHalfScore)
(Select distinct 10001 as BatchId, irt.TestID, count(*) as FirstHalfScore
From irt_TestItems irt where batchID=10001 and ItemId <=40 and TestId = irt.TestId and AnsweredCorrectly = 1 group by TestId)
Update SplitHalfTestScores
Set SecondHalfScore = (Select count(*)
From irt_TestItems irt where BatchId = 10001 and TestId = irt.TestId and irt.ItemId > 40 and AnsweredCorrectly = 1
group by TestId)
Question:What would be the best way to add carrage returns to a record, and would mymethod create alot of overhead and wasted space. What would be the bestmethod to minimize overhead and wasted space.Scenario:Server MS SQL 2000Table name= mitTicketsFields= problem,details, created, lupdateCurrent Text in record [Data Example for mitTickets.Details]Backup failed. Backup failure investigated and found tape ejected.I would like to create a stored procedure that will append the current Dateand Time to each update that is being submitted via a web form. I only wantthe web form to add text and have the stored procedure append the input textthe the existing record so that the data looks like the following.10/4/2003 9:10:32 AMTape inserted, backup completed successfully.10/4/2003 7:15:02 AMBackup failure investigated and found tape ejected.10/4/2003 6:27:08 AMBackup failed.
I have a problem where my subquery is returning two values and I need it to return only one. I believe it is doing this because of the group by DocType clause as there are two DocTypes.
Is there anyway I can sum these values in the subquery, to return only one value. This way the query should run ok.
Thanks for any help you might be able to give,
robinsql
SELECT OCRD.Cardcode, OCRD.cardname, @YearStart AS YearStart, @YearEnd AS YearEnd, @PeriodStart AS PeriodStart, @PeriodEnd AS PeriodEnd, OCRD.County, (SELECT CASE WHEN OINV.DocType = 'I' AND SUM(INV1.Quantity) <>0 THEN COALESCE(SUM(INV1.Price * INV1.Quantity), 0) ELSE COALESCE(SUM(INV1.Price), 0) END FROM INV1, OINV WHERE INV1.DocEntry = OINV.DocEntry AND OINV.CardCode = OCRD.CardCode AND OINV.DocDate >= @YearStart AND OINV.DocDate <= @YearEnd GROUP BY OINV.DocType) AS YTDInvoice, FROM OCRD, OINV WHERE CardType='C'
I'm trying to update column based upon the results of a subquery. I'm getting the error that my Subquery returns more than one result. I've tried adding the EXISTS or IN keywords and cannot get the syntax right. I can't find any examples of how to write this with an Update query.
Here's my query:
UPDATE temp_UpdateRemainingHours SET UsedHours =
(SELECT dbo.vw_SumEnteredHours_byCHARGE_CD.SumEnteredHours, dbo.vw_SumEnteredHours_byCHARGE_CD.CHARGE_CD FROM dbo.vw_SumEnteredHours_byCHARGE_CD INNER JOIN dbo.temp_UpdateRemainingHours ON dbo.vw_SumEnteredHours_byCHARGE_CD.CHARGE_CD = dbo.temp_UpdateRemainingHours.CHARGE_CD)
FROM dbo.vw_SumEnteredHours_byCHARGE_CD, temp_UpdateRemainingHours
WHERE dbo.vw_SumEnteredHours_byCHARGE_CD.CHARGE_CD = dbo.temp_UpdateRemainingHours.CHARGE_CD
I have four tables: Customer (CustomerId INT, CountyId INT), County (CountyId INT), Search(SearchId INT), and SearchCriteria (SearchCriteriaId INT, SearchId INT, CountyId INT, [others not related to this]).
I want to search Customer based off of the Search record, which could have multiple SearchCriteria records. However, if there aren't any SearchCriteria records with CountyId populated for a given Search, I want it to assume to get all Customer records, regardless of CountyId.
Right now, I'm doing it this way.
DECLARE @SearchId INT = 100 SELECT * FROM Customer WHERE CountyId IN ( SELECT CASE WHEN EXISTS(SELECT CountyId FROM SearchCriteria WHERE SearchId = @SearchId) THEN SearchCriteria.CountyId
[Code] .....
This works; it just seems cludgy. Is there a more elegant way to do this?
I want to know the differences between SQL Server 2000 storedprocedures and oracle stored procedures? Do they have differentsyntax? The concept should be the same that the stored proceduresexecute in the database server with better performance?Please advise good references for Oracle stored procedures also.thanks!!
This Might be a really simple thing, however we have just installed SQL server 2005 on a new server, and are having difficulties with the set up of the Store Procedures. Every time we try to modify an existing stored procedure it attempts to save it as an SQL file, unlike in 2000 where it saved it as part of the database itself.
hello friends.. I am newbie for sql server...I having a problem when executing this procedure .... ALTER PROCEDURE [dbo].[spgetvalues] @Uid intASBEGIN SET NOCOUNT ON; select DATEPART(year, c.fy)as fy, (select contribeamount from wh_contribute where and contribename like 'Retire-Plan B-1% JRF' ) as survivorship, (select contribeamount from wh_contribute where and contribename like 'Gross Earnings' and ) as ytdgross, (select contribeamount from wh_contribute where and contribename like 'Retire-Plan B-1.5% JRP') as totalcontrib, from wh_contribute c where c.uid=@Uid Order by fy Asc .....what is the wrong here?? " Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression."please reply asap...
I am getting 2 resultsets depending on conditon, In the secondconditon i am getting the above error could anyone help me..........CREATE proc sp_count_AllNewsPapers@CustomerId intasdeclare @NewsId intset @NewsId = (select NewsDelId from NewsDelivery whereCustomerId=@CustomerId )if not exists(select CustomerId from NewsDelivery whereNewsPapersId=@NewsId)beginselect count( NewsPapersId) from NewsPapersendif exists(select CustomerId from NewsDelivery whereNewsPapersId=@NewsId)beginselect count(NewsDelId) from NewsDelivery whereCustomerid=@CustomeridendGO
Using SQL 2005, SP2. All of a sudden, whenever I create any stored procedures in the master database, they get created as system stored procedures. Doesn't matter what I name them, and what they do.
For example, even this simple little guy:
CREATE PROCEDURE BOB
AS
PRINT 'BOB'
GO
Gets created as a system stored procedure.
Any ideas what would cause that and/or how to fix it?
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
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
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?
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.
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.
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...
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!
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
while running the following query.
SELECT DISTINCT EmployeeDetails.FirstName+' '+EmployeeDetails.LastName AS EmpName,
LUP_FIX_DeptDetails.DeptName AS CurrentDepartment,
LUP_FIX_DesigDetails.DesigName AS CurrentDesignation,
LUP_FIX_ProjectDetails.ProjectName AS CurrentProject,
ManagerName=(SELECT E.FirstName+' '+E.LastName
FROM EmployeeDetails E
INNER JOIN LUP_EmpProject
ON E.Empid=LUP_EmpProject.Empid
INNER JOIN LUP_FIX_ProjectDetails
ON LUP_EmpProject.Projectid = LUP_FIX_ProjectDetails.Projectid
WHERE LUP_FIX_ProjectDetails.Managerid = E.Empid)
FROM EmployeeDetails
INNER JOIN LUP_EmpDepartment
ON EmployeeDetails.Empid=LUP_EmpDepartment.Empid
INNER JOIN LUP_FIX_DeptDetails
ON LUP_EmpDepartment.Deptid=LUP_FIX_DeptDetails.Deptid
AND LUP_EmpDepartment.Date=(SELECT TOP 1 LUP_EmpDepartment.Date
FROM LUP_EmpDepartment
WHERE EmployeeDetails.Empid=LUP_EmpDepartment.Empid
ORDER BY LUP_EmpDepartment.Date DESC)
INNER JOIN LUP_EmpDesignation
ON EmployeeDetails.Empid=LUP_EmpDesignation.Empid
INNER JOIN LUP_FIX_DesigDetails
ON LUP_EmpDesignation.Desigid=LUP_FIX_DesigDetails.Desigid
AND LUP_EmpDesignation.Date=(SELECT TOP 1 LUP_EmpDesignation.Date
FROM LUP_EmpDesignation
WHERE EmployeeDetails.Empid=LUP_EmpDesignation.Empid
ORDER BY LUP_EmpDesignation.Date DESC)
INNER JOIN LUP_EmpProject
ON EmployeeDetails.Empid=LUP_EmpProject.Empid
AND LUP_EmpProject.StartDate=(SELECT TOP 1 LUP_EmpProject.StartDate
FROM LUP_EmpProject
WHERE EmployeeDetails.Empid=LUP_EmpProject.Empid
ORDER BY LUP_EmpProject.StartDate DESC)
INNER JOIN LUP_FIX_ProjectDetails
ON LUP_EmpProject.Projectid=LUP_FIX_ProjectDetails.Projectid
I've running the below query for months ans suddenly today started getting the following error :"Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression."
Any ideas as to why??
SELECT t0.DocNum, t0.Status, t0.ItemCode, t0.Warehouse, t0.OriginNum, t0.U_SOLineNo, ORDR.NumAtCard, ORDR.CardCode, OITM_1.U_Cultivar, RDR1.U_Variety, (SELECT OITM.U_Variety FROM OWOR INNER JOIN WOR1 ON OWOR.DocEntry = WOR1.DocEntry INNER JOIN OITM INNER JOIN OITB ON OITM.ItmsGrpCod = OITB.ItmsGrpCod ON WOR1.ItemCode = OITM.ItemCode WHERE (OITB.ItmsGrpNam = 'Basic Fruit') AND (OWOR.DocNum = t0.DocNum)) AS Expr1, OITM_1.U_Organisation, OITM_1.U_Commodity, OITM_1.U_Pack, OITM_1.U_Grade, RDR1.U_SizeCount, OITM_1.U_InvCode, OITM_1.U_Brand, OITM_1.U_PalleBase, OITM_1.U_Crt_Pallet, OITM_1.U_LabelType, RDR1.U_DEPOT, OITM_1.U_PLU, RDR1.U_Trgt_Mrkt, RDR1.U_Wrap_Type, ORDR.U_SCCode FROM OWOR AS t0 INNER JOIN ORDR ON t0.OriginNum = ORDR.DocNum INNER JOIN RDR1 ON ORDR.DocEntry = RDR1.DocEntry AND t0.U_SOLineNo - 1 = RDR1.LineNum INNER JOIN OITM AS OITM_1 ON t0.ItemCode = OITM_1.ItemCode WHERE (t0.Status <> 'L')
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
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
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!
I was comparing the parameters for two stored procs that I made using the SQL Server 2005 express management studio. Both of these sprocs only inserted one field into a single table. These were both of the type varchar.
One of the sprocs had "nocount on" and the other did not. I thought I would see the returns integer parameter in the sproc that did not have "nocount" set to on. I thought this is what returns an integer to validate an insert. Obviously, I am confused about how this works.
Can anyone help me to understand that difference between nocount on and the parameter that returns an integer.
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?
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.
Here's a really weird one for any SQL Server gurus out there...We have observed (SQL Server 2000) scenarios where a stored procedurewhich(a) begins a transaction(b) inserts some rows into a table(c) re-queries another table using a subquery which references theinserted table (correlated or not)will deadlock itself at point (c), even when it is the only task onthe server.[I use the term 'deadlock' because I can't think of anything elseappropriate, even though, as stated, this is the ONLY task executing,so this isn't a classical deadlock situation]A typical deadlocking scenario would be (assume insert_table is thetable into which some rows are being inserted)begin transactioninsert insert_table(col....) select (col....) from some_other_table/* this following query will deadlock and never complete */select some_other_table.colfrom some_other_tablewhere not exists (select *from insert_tablewhere some_other_table.col = insert_table.col )Whereas if the offending second query in the sequence is rewritten asa joine.gselect some_other_table.colfrom some_other_tableleft join insert_tableon some_other_table.col = insert_table.colwhere insert_table.col is nullthe query will not deadlock.If the subquery is an aggregate function, a deadlock will also notoccur.If the transaction is committed prior to executing the blocking query,then it will not block (hardly surprising; if it did, there'd be majorproblems with SQL Server!).Note that this is a canonical case of a much more complex SP, and thatsimplified test cases often will not deadlock; you need a significantamount of data, typically 30,000 rows or more to see the problem. Theblocking query is, in real life, used to drive a subsequent tableinsert operation, but this is not relevant to the problem.We conclude that there is some problem, possibly involving cataloguecontention, if a temporary table must be created in a subquery withina transaction in a stored procedure, and if the subquery involvesreferences to a table for which locks have been acquired.Note that the lock timeout will never trigger and a deadlock victim isnever chosen, presumably because the deadlock occurs entirely withinthe same SPID.Locking hints and transaction isolation level setting does not affectthe result. Note also that the exact same queries, executed as a TSQLbatch, do not deadlock; you must place them in a stored procedure.Recovery mode for the database is SIMPLE, and the problem is portableacross databases; it can also be exhibited with MSDE/2000, and isindependent of whether or not the database server is the local machineor not.Has anyone else experienced this problem and/or know of a workaround,other than those mentioned here?. It does look awfully like a bug withSQL Server, since a single task should never be able to deadlockitself, surely.
I'm trying to get the Rowcount from an inner select statement into an output parameter of a stored procedure. The following code returns the count from the outer select statement but when I try moving the 'SET @RecordCount = @@RowCount' line into the inner select statement I get errors. I've spent hours trying to get this to work but so far have not been able to do so.
ALTER PROCEDURE [dbo].[spProductSelectionAsp-test]
-- Add the parameters for the stored procedure here
@Product char(20) = null,
@PageSize int = 20,
@Page int = 1,
@RecordCount int = null OUTPUT
AS
BEGIN
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT TOP(@PageSize) * FROM
(
SELECT row_number() OVER (ORDER BY SKU.SIZE, SKU.COLOR) AS RowNumber,
SKUWH.RECNUM, SKUWH.AVAILABLE, SKU.STATUS, SKU.P1
FROM SKU INNER JOIN
SKUWH ON SKU.MASTER_NO = SKUWH.MASTER_NO INNER JOIN
SKUMKTG ON SKU.SKUMKTG_UID = SKUMKTG.UNIQUE_ID
WHERE (SKUMKTG.PRODUCT_# = @Product)
)
as _myResults
WHERE RowNumber > (@PageSize * (@Page - 1))
SET @RecordCount = @@RowCount
END
Any suggestions would be greatly appreciated. Thanks, Chris
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> <asp:TextBox ID="TextBox2" runat="server" TabIndex=2></asp:TextBox> <asp:Button ID="Button1" runat="server" Text="Search" TabIndex=3 /> <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>