Showing Records Where Count(*) Is Zero (in A Stored Proc)
Jul 20, 2005
This seems so easy....change the join to show all records, but the
zero records still do not show
I want to join 2 tables....basically Customers and Orders....get the
total number of orders for each Customer within a date range...but I
can't seem to show records where the total for a particular Customer
is zero (which is very important info)
I need to understand this a bit more and how to get all records out of the sp.For instance, SELECT @Name = objName FROM Structure WHERE Id = @IdI need this to return all the records, not just the last one as it seems to be doing.Do I need to adjust the code behind or the statement above?Thanks,Zath
I wrote a stored proc to be implemented in a datagrid. I went and used it on a record to update some information and it updated THE WHOLE DATABASE WITH THAT ONE RECORD..
IF anyone could shead some light on what I'm doing wrong that would be great.
Is there a way to delete records from table passing parameter as tablename? I won't to delete all records from a table dependent on table selected. i'm trying to do this with stored procedure...Table to delete depends on the checkbox selected.
Current code(works) Public Function DelAll() MZKDB = MZKHRFin If sloption = "L" Then sqlConn.ConnectionString = "Server=" & MZKSrv & ";Initial Catalog=" & MZKDB & ";Integrated Security=SSPI;" ElseIf sloption = "S" Then sqlConn.ConnectionString = "Server=" & MZKSrv & ";User id=sa;Password=" & MZKPswd & "; Initial Catalog=" & MZKDB & ";" End If sqlConn.Open() sqlTrans = sqlConn.BeginTransaction() sqlCmd.Connection = sqlConn sqlCmd.Transaction = sqlTrans Try sqlCmd.CommandText = sqlStr sqlCmd.ExecuteNonQuery() sqlTrans.Commit() frm2.txtResult.Text = frm2.txtResult.Text & " " & TableName & " Prior records have been deleted from the database." & vbCrLf SetCursor() Catch e As Exception Try sqlTrans.Rollback() Catch ex As SqlException If Not sqlTrans.Connection Is Nothing Then frm2.txtResult.Text = frm2.txtResult.Text & " " & TableName & " An exception of type " & ex.GetType().ToString() & " was encountered while attempting to roll back the transaction." & vbCrLf SetCursor() End If End Try frm2.txtResult.Text = frm2.txtResult.Text & " " & TableName & " Records were NOT deleted from the database." & vbCrLf SetCursor() Finally sqlConn.Close() End Try ResetID() End Function If cbGenFY.Checked Then sqlStr = "DELETE FROM FIN_FiscalYear" TableName = "dbo.FIN_FiscalYear" DelAll() ClearCounts() timeStepStart = Date.Now GenFY() timeStepStop = Date.Now
DispOneCounts() End If If cbGenFund.Checked Then sqlStr = "DELETE FROM FIN_Fund" TableName = "dbo.FIN_Fund" DelAll() ClearCounts() timeStepStart = Date.Now GenFund() timeStepStop = Date.Now DispOneCounts() End If If cbGenFunc.Checked Then sqlStr = "DELETE FROM FIN_Function" TableName = "dbo.FIN_Function" DelAll() ClearCounts() timeStepStart = Date.Now GenFunc() timeStepStop = Date.Now DispOneCounts()
End If If cbGenObject.Checked Then sqlStr = "DELETE FROM FIN_Object" TableName = "dbo.FIN_Object" DelAll() ClearCounts() timeStepStart = Date.Now GenObject() timeStepStop = Date.Now DispOneCounts() End If If cbGenCenter.Checked Then sqlStr = "DELETE FROM FIN_Center" TableName = "dbo.FIN_Center" DelAll() ClearCounts() timeStepStart = Date.Now GenCenter() timeStepStop = Date.Now DispOneCounts() End If If cbGenProject.Checked Then sqlStr = "DELETE FROM FIN_CodeBook" TableName = "dbo.FIN_CodeBook" DelAll() sqlStr = "DELETE FROM FIN_BudgetAccnt" TableName = "dbo.FIN_BudgetAccnt" DelAll() sqlStr = "DELETE FROM FIN_Budget" TableName = "dbo.FIN_Budget" DelAll() sqlStr = "DELETE FROM FIN_Project" TableName = "dbo.FIN_Project" DelAll() ClearCounts() timeStepStart = Date.Now GenProject() timeStepStop = Date.Now TableName = "dbo.FIN_Project" DispOneCounts() End If If cbGenProgram.Checked Then sqlStr = "DELETE FROM FIN_Program" TableName = "dbo.FIN_Program" DelAll() ClearCounts() timeStepStart = Date.Now GenProgram() timeStepStop = Date.Now DispOneCounts() End If If cbGenGL.Checked Then sqlStr = "DELETE FROM FIN_gl" TableName = "FIN_gl" DelAll() ClearCounts() timeStepStart = Date.Now GenGL() timeStepStop = Date.Now DispOneCounts() End If If cbGenRevenue.Checked Then sqlStr = "DELETE FROM FIN_Revenue" TableName = "FIN_Revenue" DelAll() ClearCounts() timeStepStart = Date.Now GenRevenue() timeStepStop = Date.Now DispOneCounts() End If If cbGenBank.Checked Then sqlStr = "DELETE FROM FIN_VendorBankAccnt" TableName = "dbo.FIN_VendorBankAccnt" DelAll() sqlStr = "DELETE FROM FIN_VendorBank" TableName = "dbo.FIN_VendorBank" DelAll() sqlStr = "DELETE FROM FIN_bankAdd" TableName = "dbo.FIN_bankAdd" DelAll() sqlStr = "DELETE FROM FIN_bankTERMS" TableName = "dbo.FIN_bankTerms" DelAll() sqlStr = "DELETE FROM FIN_bank" TableName = "dbo.FIN_bank" DelAll() ClearCounts() timeStepStart = Date.Now GenBank() timeStepStop = Date.Now TableName2 = "dbo.FIN_bankTERMS" TableName3 = "dbo.FIN_BankAdd" TableName4 = "dbo.FIN_VendorBank" TableName5 = "dbo.FIN_VendorBankAccnt" DispTwoCounts() End If If cbFinAP.Checked Then sqlStr = "DELETE FROM FIN_Period" TableName = "FIN_Period" DelAll() ClearCounts() timeStepStart = Date.Now GenPeriod() timeStepStop = Date.Now DispOneCounts() End If
I've created a sproc in SQL2000 that returns a dataset from a temp table & the number of records it's returning as an output parameter, although I can't seem to retrieve the value it's returning in asp.net although I get the dataset ok.
This is my sproc create procedure return_data_and_value @return int output as set nocount on ... ... select * from #Table select @return = count(*) from #Table drop table #Table go
This is asp.net code
Dim nRecords as Int32 Dim cmd As SqlCommand = New SqlCommand("return_data_and_value", conn) cmd.CommandType = CommandType.StoredProcedure
Dim prm As SqlParameter = New SqlParameter("@return", SqlDbType.Int) prm.Direction = ParameterDirection.Output cmd.Parameters.Add(prm)
I have a stored procedure named mySP that looks basically like this:Select Field1, Field2From tblMyTableWhere Field 3 = 'xyz'What I do is to populate an Access form:DoCmd.Openform "frmMyFormName"Forms!myFormName.RecordSource = "mySP"What I want to do in VBA is to open frmContinuous(a datasheet form) ifmySP returns more than one record or open frmDetail if mySP returnsonly one record.I'm stumped as to how to accomplish this, without running mySP twice:once to count it and once to use it as a recordsource.Thanks,lq
I am working with a large application and am trying to track down a bug. I believe an error that occurs in the stored procedure isbubbling back up to the application and is causing the application not to run. Don't ask why, but we do not have some of the sourcecode that was used to build the application, so I am not able to trace into the code. So basically I want to examine the stored procedure. If I run the stored procedure through Query Analyzer, I get the following error message: Msg 2758, Level 16, State 1, Procedure GetPortalSettings, Line 74RAISERROR could not locate entry for error 60002 in sysmessages. (1 row(s) affected) (1 row(s) affected) I don't know if the error message is sufficient enough to cause the application from not running? Does anyone know? If the RAISERROR occursmdiway through the stored procedure, does the stored procedure terminate execution? Also, Is there a way to trace into a stored procedure through Query Analyzer? -------------------------------------------As a side note, below is a small portion of my stored proc where the error is being raised: SELECT @PortalPermissionValue = isnull(max(PermissionValue),0)FROM Permission, PermissionType, #GroupsWHERE Permission.ResourceId = @PortalIdAND Permission.PartyId = #Groups.PartyIdAND Permission.PermissionTypeId = PermissionType.PermissionTypeId IF @PortalPermissionValue = 0BEGIN RAISERROR (60002, 16, 1) return -3END
I want to have all the ethnicities from the Ethnicgroup table to be displayed in a particular area which is in where clause as aggcourseid
The problem is that even when I have a left join on the EthnicGroup table it will not return all the ethnicities but will only return those who were existing in that particular aggcourseid.
i.e. If there is no African student in E2, it will not show up in the result whereas I want to display all the ethnicities and if there is no record for aggcourseid, it should show up as 0/NULL for that ethnicity.
I have tried all sorts of joins but the problem is whenever I put in the aggcourseid in where clause, it wont bring all the records
--Year 05/06 insert into #temp_et select CAST(LEFT(pv.pg_expendyrid,2) AS int)[Year], eg.pg_ethnicgroupname[Ethinicity], sum([pvstart]) [Starts],
(case when sum(pvstart) = 0 THEN 0 Else convert(decimal(6,3),(sum(pvach)*1.00)/(sum(pvstart)*1.00)*100)end)[Success], (case when sum(pvstart) = 0 THEN 0 Else convert(decimal(6,3),(sum(pvcomp)*1.00)/(sum(pvstart)*1.00)*100)end)[Retention], (case when sum(pvstart) = 0 THEN 0 Else convert(decimal(6,3),(sum(pvach)*1.00)/(sum(pvcomp)*1.00)*100)end)[Achievement] --into temp_et from [FECAS].Proachieve.dbo.pv_midpoint pv left join [FECAS].Proachieve.dbo.GN_AggCourseStructure gn on pv.pg_aggcourseid = gn.pg_aggcourseid left join [FECAS].Proachieve.dbo.PG_ethnicGroup eg on pv.pg_ethnicgroupid = eg.pg_ethnicgroupid
where pv_midpointid = @mpid and pg_expendyrid = '05/06'
and pv.pg_aggcourseid LIKE 'E2%'
group by eg.pg_ethnicgroupname, pv.pg_expendyrid order by eg.pg_ethnicgroupname
I am having trouble executing a stored procedure on a remote server. On my local server, I have a linked server setup as follows: Server1.abcd.myserver.comSQLServer2005,1563
This works fine on my local server:
Select * From [Server1.abcd.myserver.comSQLServer2005,1563].DatabaseName.dbo.TableName
This does not work (Attempting to execute a remote stored proc named 'Data_Add':
When I attempt to run the above, I get the following error: Could not locate entry in sysdatabases for database 'Server1.abcd.myserver.comSQLServer2005,1563'. No entry found with that name. Make sure that the name is entered correctly.
Could anyone shed some light on what I need to do to get this to work?
Hi All,Quick question, I have always heard it best practice to check for exist, ifso, drop, then create the proc. I just wanted to know why that's a bestpractice. I am trying to put that theory in place at my work, but they areasking for a good reason to do this before actually implementing. All Icould think of was that so when you're creating a proc you won't get anerror if the procedure already exists, but doesn't it also have to do withCompilation and perhaps Execution. Does anyone have a good argument fordoing stored procs this way? All feedback is appreciated.TIA,~CK
I have an ASP that has been working fine for several months, but itsuddenly broke. I wonder if windows update has installed some securitypatch that is causing it.The problem is that I am calling a stored procedure via an ASP(classic, not .NET) , but nothing happens. The procedure doesn't work,and I don't get any error messages.I've tried dropping and re-creating the user and permissions, to noavail. If it was a permissions problem, there would be an errormessage. I trace the calls in Profiler, and it has no complaints. Thedatabase is getting the stored proc call.I finally got it to work again, but this is not a viable solution forour production environment:1. response.write the SQL call to the stored procedure from the ASPand copy the text to the clipboard.2. log in to QueryAnalyzer using the same user as used by the ASP.3. paste and run the SQL call to the stored proc in query analyzer.After I have done this, it not only works in Query Analyzer, but thenthe ASP works too. It continues to work, even after I reboot themachine. This is truly bizzare and has us stumped. My hunch is thatwindows update installed something that has created this issue, but Ihave not been able to track it down.
I have a report with 5 filters which can be applied to it. The records are grouped by the Rotation programme there are on, with a subtotal for each unique programme name.
The report seems to work fine, but upon closer inspection - we noticed that 2 of the records are not being displayed. As a result, the total count is out by 2.
We tracked down the missing records so I ran the SQL query with a Where clause, and it was able to find the two records.
What could possibly cause this behaviour? Please see included SQL statement :
Code Block
SELECT Posts.PostNumber,COUNT(Posts.PostNumber) AS RPCount, Incumbents.Name AS IncumbentName, Grades.GradeTitle, Specialties.SpecialtyTitle, Hospitals.Name AS Hospital, Genders.Gender, [Incumbent History].YearGraduated, COUNT([University Origins].Origin) AS OriginCount, Incumbents.Nationality AS NationalityID, Countries.[Country Name] AS Nationality, [Rotation Programmes].[Programme Name], Posts.[Post Approved for Training], [University Origins].Origin, Posts.OldPostNumber, [Rotation Programmes].[Programme ID] FROM Posts INNER JOIN Incumbents ON Posts.PostNumber = Incumbents.PostNumber INNER JOIN [Incumbent History] ON Incumbents.[Incumbent ID] = [Incumbent History].IncumbentID INNER JOIN Grades ON Incumbents.[Official Grade] = Grades.GradeID INNER JOIN Specialties ON Posts.Specialty = Specialties.SpecialtyID INNER JOIN Hospitals ON Posts.HospitalID = Hospitals.[Hospital ID] INNER JOIN Genders ON Incumbents.GenderID = Genders.GenderID INNER JOIN Countries ON Incumbents.[Country Of Birth] = Countries.[Country ID] INNER JOIN [Rotation Programmes] ON Posts.[Rotation Programme] = [Rotation Programmes].[Programme ID] INNER JOIN [University Origins] ON [University Origins].[Uni Origin ID] = Incumbents.[University Origin]
GROUP BY [Rotation Programmes].[Programme Name], Posts.PostNumber, Incumbents.Name, Grades.GradeTitle, Hospitals.Name, Genders.Gender, [Incumbent History].YearGraduated, [University Origins].Origin, Incumbents.Nationality, Countries.[Country Name], [University Origins].Origin, Posts.[Post Approved for Training], Posts.OldPostNumber, Specialties.SpecialtyTitle, [Rotation Programmes].[Programme ID]
my table does not have primary key so i created a seperate index on each of the table.
I used the recommended tablediff utility and it works successfully. But its only show the difference of records in each table and does not copy rows from source to destination and destination to source table. I was expecting database1.dbo.table1 contains same records as in database1.dbo.table2.
C:Program FilesMicrosoft SQL Server90COM>tablediff /sourceserver kashif-pcs qlexpress /sourcedatabase AB /sourcetable table1 /destinationserver kashif-pcsq lexpress /destinationdatabase CD /destinationtable table2 Microsoft (R) SQL Server Replication Diff Tool Copyright (C) 1988-2005 Microsoft Corporation. All rights reserved.
User-specified agent parameter values: /sourceserver kashif-pcsqlexpress /sourcedatabase AB /sourcetable table1 /destinationserver kashif-pcsqlexpress /destinationdatabase CD /destinationtable table2
Table [AB].[dbo].[table1] on kashif-pcsqlexpress and Table [CD].[dbo].[table2] on kashif-pcsqlexpress have 5 differences. Err Sno Src. Only 101 Src. Only 102 Dest. Only 103 Dest. Only 104 Dest. Only 105 The requested operation took 0.466767 seconds.
Can you write a short script for my problem, just like comparison of database1.dbo.table1 compares in database2.dbo.table2 and which ever records not present it should copy those and vice-versa.
It means Database1.dbo.table1 contains 5 records Database2.dbo.table2 contains 5 records
I have a stored procedure "uspX" that calls another stored procedure "uspY" and I need to retrieve the return value from uspY and use it within uspX. Does anyone know the syntax for this?
I have about 5 stored procedures that, among other things, execute exactly the same SELECT statement
Instead of copying the SELECT statement 5 times, I'd like each stored proc to call a single stored proc that executes the SELECT statement and returns the resultset to the calling stored proc
The SELECT statement in question retrieves a single row from a table containing 10 columns.
Is there a way for a stored proc to call another stored proc and gain access to the resultset of the called stored proc?
I know about stored proc return values and about output parameters, but I think I am looking for something different.
I would like to know if the following is possible/permissible:
myCLRstoredproc (or some C# stored proc) { //call some T SQL stored procedure spSQL and get the result set here to work with
INSERT INTO #tmpCLR EXECUTE spSQL }
spSQL (
INSERT INTO #tmpABC EXECUTE spSQL2 )
spSQL2 ( // some other t-sql stored proc )
Can we do that? I know that doing this in SQL server would throw (nested EXECUTE not allowed). I dont want to go re-writing the spSQL in C# again, I just want to get whatever spSQL returns and then work with the result set to do row-level computations, thereby avoiding to use cursors in spSQL.
if @persontype<>"" begin set @cond= @cond+"and persontype="+@persontype end if @name<>"" begin set @cond= @cond+"and (charindex("+@name+",x_firstname)>0 or charindex("+@name+",x_lastname)>0 or charindex("+@name+",x_email)>0) " end if @activeaccount<>-1 begin set @cond= @cond+'and activeaccount='+@activeaccount end if @adddatetime<>"" begin set @cond= @cond+'and adddatetime='+@adddatetime end if @country<>"" begin set @cond= @cond+'and x_country='+@country end print @cond exec( " select * from users where 1=1 "+@cond) GO
Well I am not sure if I am doing something wrong but after having created a stored procedure I did the following. I hit the parse script button to check the script, it came back fine. I then executed the script which completed fine. But to my amazement the procedure did not show. I hit the refresh button to no avail I stopped and started the server services. Then I tried to run it again this time it tells me that that it allready exists. Here is the sp any help would be greatly appreciated.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Shawn Jones
-- Create date: 03/19/06
-- Description: Update Avl Status of machine
-- =============================================
CREATE PROCEDURE [dbo].[sp_Update_Machine_Status]
-- Add the parameters for the stored procedure here
@Avl bit = False,
@Name nvarchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
i have this function it return 0 but the sql statement in the sql query return the right number?how is that i want to get the number of records any other idea or fix? Public Function UserAlbumPhotoQuota(ByVal userID As Integer) As BooleanDim Conn As New SqlConnection(ConfigurationManager.ConnectionStrings("Conn").ConnectionString) Dim strSQL As StringDim dr As SqlDataReader strSQL = "SELECT *, (select count(*) from userAlbumPic where userID=" & userID & ") as rec_count from userAlbumPic "Dim cmd As New SqlCommand()cmd = New SqlCommand(strSQL, Conn) Conn.Open() dr = cmd.ExecuteReader() dr.Read()userQuota = dr("rec_count").ToString Conn.Close() End Function
Hello All, I'm wondering if you guys can help me with a problem to count every record in a table; however, I must match this table with another table to get the category names. I have tried this SQL statement in the SQL Express and it works very great. SELECT aspnet_Category.CategoryName, COUNT(*) AS Expr1FROM aspnet_Category INNER JOINaspnet_resources ON aspnet_Category.ApplicationID = aspnet_resources.ApplicationId AND aspnet_Category.CategoryID = aspnet_resources.CategoryIDGROUP BY aspnet_Category.CategoryNameORDER BY aspnet_Category.CategoryName However, when I tried to put this into my code, it gives me a error. <System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, True)> _Function GetDataByCount_CategoryID() As CategoryDataTableGetDataByCount_CategoryID = Adapter.GetDataByCount_CategoryIDEnd FunctionFailed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints. Can you please help me to fix this error? Thank you, Vic.
I need to export records to a text file and simply index them. i.e. in the pipe delimited file I need a column with the ordinal value of each row. Example:
1|"Jane Doe"|"23 Western ave"|... 2|"Jamie Delom"|"5 East Street|... 3|"Nat Girshon"|"5678 Main Street|... . .
Would anyone be able to tell me how I could build this within the SQL query without creating a physical table and using IDENTITY functions?
Hi i am just an beginner with sql and i am quite sure this will be a simple question i am looking for a methode to count the number of records how can i do this?
I am calling a stored procedure (say X) and from that stored procedure (i mean X) i want to call another stored procedure (say Y)asynchoronoulsy. Once stored procedure X is completed then i want to return execution to main program. In background, Stored procedure Y will contiue his work. Please let me know how to do that using SQL Server 2000 and ASP.NET 2.
I have the following: Dim ResourceAdapter As New ResourcesTableAdapters.ResourcesTableAdapter Dim dF As Data.DataTable = ResourceAdapter.GetDataByDistinct Dim numRows = dF.Rows.Count Dim dS As Data.DataTable = ResourceAdapter.CountQuery Dim sumRows = dS.Rows.Count DataList1.DataSource = dF DataList1.DataBind() LblCount.Text = numRows LblSum.Text = sumRows numRows is the number of records in a particular category. CountQuery is a method that returns the total number of records in all the categories. I don't know how to get the result of that query, the code line in bold isn't right. How do I get this number?Diane
Hello, I am writing a piece of code in ASP.NET and I'd like to get the # of records on a table and used this code: Dim ConnString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='G:Aco ProntoBSCBSC_v1.mdb'"Dim Con As New OleDbConnection(ConnString) Dim Cmd As New OleDbCommand("SELECT COUNT(*) AS Expr1 FROM Metricas", Con)Dim reader As OleDbDataReader Con.Open() reader = Cmd.ExecuteReader()Dim NumMetr As Integer = Val(reader("Expr1")) reader.Close() Con.Close()
I am getting an error that that's no data in the table. Any suggestions?
Hello, I am having problems with this query below: 1 SELECT Table1.Email AS Email, 2 Table2.UserName AS Username, 3 Table3.Members_Paid AS Paid, 4 (SELECT DISTINCT COUNT(*) 5 FROM Table3 AS e JOIN Table3 AS m 6 ON e.Members_Sponsor = m.Members_ID 7 WHERE (e.Members_Sponsor = m.Members_ID)) AS TotalRecords 8 FROM Table1 INNER JOIN 9 Table2 ON Table1.UserId = Table2.UserId INNER JOIN 10 Table3 ON Table2.UserId = Table3.UserID 11 WHERE (Table3.Members_Sponsor = @UserId)Basicly what I am trying to do is get all members that belong to a certain manager along with those members count total of members they have below them.The code above is giving me the count of the first member only, not different counts for each member.Hope you understand what I am trying to say and do here. Hope someone can help me out cause this hase been driving me crazy for a few days now.
hi can anyone tell me how to count number of records(rows) in a table without using "COUNT" function.for practise iam trying to implement it through queries.
I'm having problems constructing a query. I need to get a count of emails in my database, but only the emails that appear 2 or more times. Can anyone help?