Combine Multiple Select Statements from different tables - c#

i have the this MYSQL SP that does SUm against different tables but i wanted the SP to return all the results in one table one row i tried using + to combine results from the selects but it gets error
DROP PROCEDURE IF EXISTS x.GetFinanceContent;
delimiter //
CREATE PROCEDURE x.GetFinanceContent
(
IN userId INT
)
BEGIN
(SELECT SUM(AMOUNT) AS creditTotal
FROM x.Card1
WHERE user_Id = userId and card_type=1)
+
(SELECT SUM(AMOUNT) AS debitTotal
FROM x.Card2
WHERE user_Id = userId and card_type=2)
END;//
Error Code: 1064 You have an error in
your SQL syntax; check the manual that
corresponds to your MySQL server
version for the right syntax to use
near '+ (SELECT SUM(AMOUNT) AS
debitTotal
FROM x.Card
WHERE user_Id ' at line 10 0.000 sec

SELECT
( SELECT SUM(AMOUNT) AS creditTotal
FROM x.Card1
WHERE user_Id = userId AND card_type=1
)
, ( SELECT SUM(AMOUNT) AS debitTotal
FROM x.Card2
WHERE user_Id = userId AND card_type=2
)

If you want to SUM those sums you can make query like this:
SELECT ((SELECT SUM(AMOUNT) AS creditTotal
FROM x.Card1
WHERE user_Id = userId and card_type=1) +
(SELECT SUM(AMOUNT) AS debitTotal
FROM x.Card2
WHERE user_Id = userId and card_type=2)) as total
Use union http://dev.mysql.com/doc/refman/5.0/en/union.html If you want to get one result set....
DROP PROCEDURE IF EXISTS x.GetFinanceContent;
delimiter //
CREATE PROCEDURE x.GetFinanceContent
(
IN userId INT
)
BEGIN
(SELECT SUM(AMOUNT) AS creditTotal
FROM x.Card1
WHERE user_Id = userId and card_type=1)
UNION
(SELECT SUM(AMOUNT) AS debitTotal
FROM x.Card2
WHERE user_Id = userId and card_type=2)
END;//
Although I am rusty now with SQL and too lazy to check if syntax is correct, I think it should work.

Related

How to Count the Total Number of Rows Across Multiple Tables stored procedure in c#

I have some tables. I just want to show it in a pay chart as a percentage. How many rows have a table? I try to count all rows and store them in a variable. I have a DTO model class. That class contains All the properties same Stored procedure variables. The results are exactly the same as our expected results. But when I try to invoke the stored procedure then shows an error. But when I Pass a single variable then it works well.
ALTER PROCEDURE [dbo].[GetTotalNumberOfFormsSubmitted]
AS
BEGIN
(select BurnOut = count(*) from Client_BurnOuts
UNION ALL
select CIP = count(*) from Client_CIPEnergyCrisises
UNION ALL
select HomeRepair = count(*) from Client_HomeRepairs
UNION ALL
select MadicalTravelAssistan = count(*) from Client_MedicalTravelAssistances
UNION ALL
select EmergencyAssistance = count(*) from Client_EmergencyAssistances
UNION ALL
select Heating = count(*) from Client_Heatings
UNION ALL
select DuckFoundation = count(*) from Client_DukeEnergyFoundations
UNION ALL
select FoodPantry = count(*) from Client_EmergencyFoodPantries
UNION ALL
select MedicalEquipment = count(*) from Client_MedicalEquipments)
END
finally solved my problem, that is my solution
ALTER PROCEDURE [dbo].[GetTotalNumberOfFormsSubmitted]
AS
BEGIN
select
br.BurnOut, ho.HomeRepair, cip.CIPEnergyCrisises, mta.MadicalTravelAssistan, ea.EmergencyAssistance, he.Heating
from
(select BurnOut = count(*) from Client_BurnOuts) as br,
(select HomeRepair = count(*) from Client_HomeRepairs) as ho,
(select CIPEnergyCrisises = count(*) from Client_CIPEnergyCrisises) as cip,
(select MadicalTravelAssistan = count(*) from Client_MedicalTravelAssistances) as mta,
(select EmergencyAssistance = count(*) from Client_EmergencyAssistances) ea,
(select Heating = count(*) from Client_Heatings) as he,
(select DuckFoundation = count(*) from Client_Heatings) as du,
(select FoodPantry = count(*) from Client_Heatings) as fp,
(select MedicalEquipment = count(*) from Client_Heatings) as me
END

how to write this query in access 2007

select ((select SUM (Total)
from Shirt_Mes
where CustomerId =2
and Created_Date ='2016-10-05 05:25:06.000')
+ (select SUM (Total)
from Pant_Mes
where CustomerId =2
and Created_Date ='2016-10-05 05:25:06.000' )
MS Access requires a FROM clause with a table. So, let's move both to the FROM clause. There are a few other changes as well:
select s.sums + p.sump
from (select SUM(Total) as sums
from Shirt_Mes
where CustomerId = 2 and
Created_Date = #10/5/2016# -- different date format
) as s, -- Oh, it hurts that MS Access does not have `cross join`
(select SUM(Total) as sump
from Pant_Mes
where CustomerId = 2 and
Created_Date = #10/5/2016#
) as p;

Getting error of "Top clause contains invalid value" on front end but in SQL Data is clearly visible

While binding data to Dataview getting this error but Parameters are correctly sending there values.
Seems DBhelper class is throwing this error but don't know why
My procedure:
insert #leads(opp_lead,opp_NAME,CNT)
select opp_lead,'LEAD'+opp_lead,COUNT(*) from #pipeline GROUP BY opp_lead
UPDATE #leads SET opp_NAME=CONTACT_NAME FROM TBLCONTACT C, #leads L WHERE CONVERT(VARCHAR(50),L.opp_lead)=CONVERT(VARCHAR(50),C.CONTACT_ID)
COUNT(*) DESC
create table #YearlyEndCampaign
(
slno INT ,
lvl int
)
SELECT TOP 1 #MAXLEADS=COUNT(*) FROM #pipeline GROUP BY opp_lead ORDER BY COUNT(*) DESC
INSERT INTO #YearlyEndCampaign(slno,LVL)
SELECT SEQ,0 FROM (SELECT TOP (#MAXLEADS) seq = ROW_NUMBER() OVER (ORDER BY number) FROM [master]..spt_values)S
C# code:
long businessID = Convert.ToInt64(Session["BusinessID"]);
long YEAR = Convert.ToInt64(2015);
long UserID = Convert.ToInt64(Session["Contact_ID"]);
BeggingDA objBeggingDA = new BeggingDA();
DataView dv = (new BeggingDA()).BeggingLoadByBusinessID(YEAR, businessID, UserID);
As you say, the first SELECT TOP 1 #MAXLEADS=COUNT(*) FROM #pipeline statement is not returning any data. This means that #MAXLEADS is null.
If you then run select top (NULL) FROM [master]..spt_values you will get the TOP clause contains an invalid value error, because you are not passing a numeric value to TOP.
The solution is to check if #MAXLEADS is null before doing the insert - if there aren't any rows, you would be selecting top 0, so it is pointless doing the insert anyway. A simple IF #MAXLEADS IS NOT NULL should be sufficient:
SELECT TOP 1 #MAXLEADS=COUNT(*) FROM #pipeline GROUP BY opp_lead ORDER BY COUNT(*) DESC
IF #MAXLEADS IS NOT NULL BEGIN
INSERT INTO #YearlyEndCampaign(slno,LVL)
SELECT SEQ,0 FROM (SELECT TOP (#MAXLEADS) seq = ROW_NUMBER() OVER (ORDER BY number) FROM [master]..spt_values)S
END

How to get the total count of two columns from two different tables in SQL Server?

I have 2 tables in SQL Server, Table1 and Table2.
Table1 contains the information of family head with his age and Table2 contains the information of family members with their age.
I want to get total count of age. Means if the user enter less than 23 in front end so I will display to user total count of persons less than 23 age from two tables.
My approach is like this:
alter procedure example
(#age int, #result2 int output)
as
begin
declare #result int;
declare #result1 int;
set #result = (select count(age) from Table1 where age > #age)
set #result1 = (select count(age) from Table2 where age > #age)
set #result2 = #result + #result1;
end
hvcid is the primary key column in my Table1 and hvcid is a foreign key in my Table2.
My query shown above returns the result fine. Why not do using join or single query to combine two tables and get the total count of age from two tables?
I don't know how to write using single query? Can you solve my issue?
You can use below query to get result from 2 tables :
select count(age) + (select count(age)
from Table2 where age > #age)
from Table1 where age > #age
Another way
SELECT Sum(cnt) AS total
FROM (SELECT Count(age) cnt
FROM Table1
WHERE age > #age
UNION ALL
SELECT Count(age)
FROM Table2
WHERE age > #age) a
Try this #Nag
select (COUNT(t1.age) + COUNT(t2.age)) as Result
from Table1 t1
FULL JOIN Table2 t2 on t1.hvcid = t2.hvcid
where t1.age > #age and t2.age > #age

Parameters to the EXISTS clause in a stored procedure

I have a table DEPT, which holds 2 columns - ID, NAME.
A search form is presented with the IDs from the DEPT table and the user can chose any number of IDs and submit the form, to get the related NAMEs.
Clarification/Inputs:
I don't want to build a dynamic query - its not manageable.
I prefer a stored procedure using table-valued parameters
Any other solutions to proceed?
NOTE:
This example is simple with 1 table - in real life, I have to deal with more than 6 tables!
Thanks for any suggestions
CREATE TYPE dbo.DeptList
AS TABLE
(
ID INT
);
GO
CREATE PROCEDURE dbo.RetrieveDepartments
#dept_list AS dbo.DeptList READONLY
AS
BEGIN
SET NOCOUNT ON;
SELECT Name FROM dbo.table1 WHERE ID IN (SELECT ID FROM #dept)
UNION ALL
SELECT Name FROM dbo.table2 WHERE ID IN (SELECT ID FROM #dept)
-- ...
END
GO
Now in your C# code, create a DataTable, fill it in with the IDs, and pass it in to the stored procedure. Assuming you already have a list called tempList and the IDs are stored in id:
DataTable tvp = new DataTable();
tvp.Columns.Add(new DataColumn("ID"));
foreach(var item in tempList)
{
tvp.Rows.Add(item.id);
}
using (connObject)
{
SqlCommand cmd = new SqlCommand("StoredProcedure", connObject);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter tvparam = cmd.Parameters.AddWithValue("#dept_list", tvp);
tvparam.SqlDbType = SqlDbType.Structured;
...
}
You can also use a split function. Many exist, this is the one I like if you can guarantee that the input is safe (no <, >, & etc.):
CREATE FUNCTION dbo.SplitInts_XML
(
#List VARCHAR(MAX),
#Delimiter CHAR(1)
)
RETURNS TABLE
AS
RETURN
(
SELECT Item = y.i.value('(./text())[1]', 'int')
FROM
(
SELECT x = CONVERT(XML, '<i>'
+ REPLACE(#List, #Delimiter, '</i><i>') + '</i>').query('.')
) AS a
CROSS APPLY x.nodes('i') AS y(i)
);
GO
Now your procedure can be:
CREATE PROCEDURE dbo.RetrieveDepartments
#dept_list VARCHAR(MAX)
AS
BEGIN
SET NOCOUNT ON;
;WITH d AS (SELECT ID = Item FROM dbo.SplitInts(#dept_list, ','))
SELECT Name FROM dbo.table1 WHERE ID IN (SELECT ID FROM d)
UNION ALL
SELECT Name FROM dbo.table2 WHERE ID IN (SELECT ID FROM d)
-- ...
END
GO

Categories