How can we assign local variable in sub query SQL Server - c#

I tried to set a value to variable in sub query but it doesn't work.
Here is my query:
declare #val1 int
declare #val2 int
select #val1 = sum(column1)
,(select #val2 = (select sum(column2) from table2))
,(#val1+#val2)Result
from table 1
What I want to do is setting #val2 for sub query help me please
I meant set in Sub query not separate select statement

Just use 3 separate selects:
select #val1 = sum(column1) from table1
select #val2 = sum(column2) from table2
select (#val1+#val2) as Result
Or you can also write 2 selects:
select #val1 = sum(column1),
#val2 = (select SUM(column2) from table2)
from table1
select (#val1 + #val2) Result
But not just 1 select:
A SELECT statement that assigns a value to a variable must not be
combined with data-retrieval operations
If you need to accomplish all in one select and return a recordset, do not use variables, do it like this:
SELECT sum1 + sum2 FROM (
select sum(column1) as sum1,
(select SUM(column2) from table2) as sum2
from table1
) subquery

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 select values from 3 tables + count()

I have three Tables :
tbl_Publisher [Publisher_ID, addr,account-num,...,city];
tbl_Title [Title_ID, frequency, publisher,.., Publisher_ID];
tbl_Invoice [Invoice_ID, ordered_Date,...,Title_ID];
I would like to return a list of Titles by Publisher and each Title has the count number of Invoices it contains. in one result set.
I'm using a stored procedure as following :
PROCEDURE [dbo].[usp_GetTitlesbyPublisher]
-- Add the parameters for the stored procedure here
#PublisherID INT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
-- Insert statements for procedure here
SELECT Title_ID,TitleName,pub_type,Frequency , Holdings ,tbl_Title.publisher ,section ,tbl_Title.Publisher_ID from tbl_Title, tbl_Publisher
where tbl_Title.Publisher_ID = tbl_Publisher.Publisher_ID
and #PublisherID = tbl_Publisher.Publisher_ID
END
How can I return the number of Invoice by each Title ?
You can probably accomplish this with a GROUP BY:
SELECT t.Title_ID, t.TitleName, p.pub_type,
t.Frequency, Holdings, t.publisher, section,
t.Publisher_ID, count(i.Invoice_ID) as NoOfInvoices
from tbl_Title t
inner join tbl_Publisher p on t.Publisher_ID = p.Publisher_ID
left join tbl_Invoice i on i.Title_ID = t.Title_ID
where #PublisherID = p.Publisher_ID
group by t.Title_ID, t.TitleName, p.pub_type, t.Frequency,
Holdings, t.publisher, section, t.Publisher_ID
Not checked the syntax on this.
SELECT COUNT(tbl_Invoice.Invoice_ID) 'InvoiceCount',Title_ID,TitleName,pub_type,Frequency, Holdings ,tbl_Title.publisher ,section ,tbl_Title.Publisher_ID
FROM tbl_Title
INNER JOIN tbl_Publisher ON tbl_Publisher.Publisher_ID = tbl_Title.Publisher_ID
INNER JOIN tbl_Invoice ON tbl_Invoice.Invoice_ID = tbl_Title.Invoice_ID
WHERE tbl_Publisher.Publisher_ID = #PublisherID
GROUP BY
Title_ID,TitleName,pub_type,Frequency, Holdings ,tbl_Title.publisher ,section ,tbl_Title.Publisher_ID

SQL case for selecting table

I have to query from a table or a view on two condition. I could repeat it with if conditions, but in my scenario it need to be in one query,
Something like a procedure that is receiving a flag #reportType int
SELECT
a, b, c, d, e, f, g, h,... and so many
FROM
CASE
WHEN #reportType = 1
THEN table
ELSE View
END
INNER JOIN
and so on..
I need to write like above but it is throwing an error
Incorrect syntax near the keyword 'CASE'
In your stored procedure, you need to use an if statement instead:
if #reportType=1
SELECT a,b,c FROM myTable
else
SELECT a,b,c FROM myView
Actually this does not look like a good design, but if you have to work with this and wish to avoid copy-past, you may try conditional CTEs with final union or one subquery with union to imitate single source for final query:
;with Source_1 as
(
select ...
from myTable
where #reportType=1
),
Source_2 as
(
select ...
from myView
where #reportType=2
),
FullSource
(
select ...
from Source_1
union all
select ...
from Source_2
)
select ...
from FullSource src
inner join ...
or
select ...
from
(
select ...
from myTable
where #reportType = 1
union all
select ...
from myView
where #reportType = 2
) src
inner join ...
Note, different possible flows confuse query optimizer and this code is not good for performance. For some better execution plan you will probably need to enable recompile option.
You can use dynamic SQL as below:
DECLARE #reportType INT
SET #reportType = 1
DECLARE #q VARCHAR(max)= 'SELECT
a, b, c, d, e, f, g, h,... and so many
FROM '+
CASE
WHEN #reportType = 1
THEN 'table '
ELSE 'View '
END+'
INNER JOIN
and so on..'
EXEC(#q)
You may also want to use sp_executesql in order to make the query parametric and prevent the possible SQL injection.
I think you need a query like this:
;WITH mixedData AS (
SELECT yourFields, 1 As reportType
FROM yourTable
UNION ALL
SELECT yourFields, 2 AS reportType
FROM yourView
)
SELECT *
FROM mixedData
INNER JOIN yourJoinParams
WHERE mixedData.reportType = #reportType;
or
...
WHERE mixedData.reportType =
CASE WHEN #reportType = 1 THEN 1 ELSE 2 END;
Note that yourFields from yourTable and yourView are same.
HTH

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

C# T-SQL Join and Union

I have a question regarding joining tables.
I have eleven tables, one parent with ten child tables. Primary key on all is EventName with the relationship from parent to child being EventName as well. The child tables names are SR1Laptimes, SR2Laptimes etc x 10.
The schema in the child tables are identical. I'm trying to join Events table to SR1Laptimes and then Union all the child table together but can't get it to work.
There is a method behind this madness but would take some time to explain. Here's the code anyway, any feed back would be greatly appreciated. P.S the codes not finished in this copy and paste.
myCommand.CommandText = "SELECT MIN(Q1), MIN(Q2), MIN(Q3), MIN(Q4), MIN(LaptimesMinutes), MIN(LaptimesSeconds) FROM Events LEFT JOIN SR1Laptimes ON Events.EventName = SR1Laptimes.EventName SELECT * FROM SR1Laptimes UNION ALL SELECT * FROM SR2Laptimes UNION ALL SELECT * FROM SR3Laptimes WHERE (Events.Track = #track) AND (Events.Number = #number) AND (Events.Rider = #rider)";
myCommand.Parameters.AddWithValue("#track", analysisTrackComboBox.Text);
myCommand.Parameters.AddWithValue("#number", analysisNumberComboBox.Text);
myCommand.Parameters.AddWithValue("#rider", analysisRiderComboBox.Text);
I think you are missing an UNION ALL clause at:
... ON Events.EventName = SR1Laptimes.EventName *HERE* SELECT * FROM SR1Laptimes ...
Are the tables you try to 'union all' have same columns? That might be the problem.
And 'where' clause at the end is valid only for SR3Laptimes.
This example may help you.
DECLARE #Parent TABLE (id INT,sth NVARCHAR(100))
DECLARE #ChildTest1 TABLE(id INT,parentId INT, sth NVARCHAR(100))
DECLARE #ChildTest2 TABLE(id INT, parentId INT, sth NVARCHAR(100))
INSERT INTO #Parent
SELECT 1,'Ali'
UNION ALL
SELECT 2,'Veli'
UNION ALL
SELECT 3,'Ahmet'
INSERT INTO #ChildTest1
SELECT 1,1,'Parent1_Child1_1strow'
UNION ALL
SELECT 2,1,'Parent1_Child1_2ndrow'
UNION ALL
SELECT 3,2,'Parent2_Child1_1strow'
INSERT INTO #ChildTest2
SELECT 1,1,'Parent1_Child2_1strow'
UNION ALL
SELECT 2,2,'Parent2_Child2_1strow'
UNION ALL
SELECT 3,3,'Parent3_Child2_1strow'
SELECT * FROM #Parent p
LEFT JOIN (
SELECT * FROM #ChildTest1 ct1
UNION ALL
SELECT * FROM #ChildTest2 ct2
) s ON p.id =s.parentId
--WHERE p.id = 3

Categories