Getting time out exception when run this query from vs - sql

this are the my table structure i need each category subcategory's count and question count of the related category where Isparent=1 from category table this is my result table
This is my code
My prob is it run in sql server while running from application(VS) it throw a time our error
where i did mistake help me out frnds.
thanks in advance.
DECLARE #TEMP TABLE (CategoryID INT,NAME VARCHAR(52))
INSERT INTO #TEMP SELECT CategoryID,Name FROM EC_M_CategoriesMaster where IsParent=1
DECLARE #TEMP1 TABLE ( CategoryID INT,cCOUNTS INT)
INSERT INTO #TEMP1 SELECT te.CategoryID,COUNT((ISNULL(te1.PCategoryID,0)))
AS Ccount from #TEMP te inner join EC_M_CategoriesMaster te1 on te.CategoryID=te1.PCategoryID GROUP BY te.CategoryID
DECLARE #TEMP2 TABLE (CategoryID INT,COUNTS INT )
INSERT INTO #TEMP2 SELECT CategoryID,COUNT((ISNULL(QuestionID,0)))
AS Qcount from EC_M_QuestionMaster GROUP BY CategoryID
SELECT t1.CategoryID,t1.Name,ISNULL(t.COUNTS,0) as Qcount,ISNULL(MY.cCOUNTS,0) AS CatCount from
#TEMP2 t RIGHT OUTER JOIN
#TEMP t1 ON t.CategoryID=t1.CategoryID
LEFT JOIN #TEMP1 MY ON MY.CategoryID=T1.CategoryID

Related

SQL Server hierarchy referencing and cross data referencing

This might be a stupid question, but I am not a DBA and kind of stuck with this issue. I have an application that trickles down all effects (asdf) under an applied ID (IDParent).
The data tables are setup like this:
Data Tables
3rd Data Table
I want to write a query that when using IDChild it will reference that entry's IDParent to get the parent ID while referencing it as an IDChild. For example for the data entry starting at 116 I want to use the parent ID (124) and get 321 in T1. I want to use this to get the RandoName associated with RandoID for all of the entries that has a parent ID of 321.
Right now I am using a script something like:
Select t.[NAME]
From T2 tv
Inner join T3 t on t.RandoID = tv.RandoId
Where
tv.IDChild = T1.IDChild OR tv.IDChild = T1.IDParent
but I'm not sure how to get the whole applied hierarchy.
This would yield something like this:
Resulting Query
PS. I can not change the tables/db schema. But maybe I can add one to do all the referencing? Please tell me what you think.
EDIT I'm sorry I forgot about this other stupid table that RandoID uses which contains the name of the RandoID. I am trying to get the name of RandoID
I think a loop could help you.
Try this:
CREATE TABLE #t1 (IDChild Int, IDParent Int);
CREATE TABLE #t2 (RandoID NVARCHAR(10) , IDChild Int);
CREATE TABLE #RandoName (RandoID NVARCHAR(10), RandoName VARCHAR(50));
INSERT INTO #t1 VALUES (321, NULL), (123,321),(124,123),(116,124)
INSERT INTO #t2 VALUES ('asdf', 123)
INSERT INTO #RandoName VALUES ('asdf', 'something')
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 100)) [RowNum], a.IDChild a, a.IDParent b, b.IDChild c INTO #t3 FROM #t1 a
LEFT OUTER JOIN #t1 b ON b.IDParent = a.IDChild
DECLARE #rownum INT;
DECLARE cbcursor CURSOR for Select RowNum FROM #t3;
OPEN cbcursor;
Fetch Next from cbcursor into #rownum
WHILE ##FETCH_STATUS = 0
BEGIN
UPDATE #t3
SET c = (SELECT b from #t3 where RowNum = #rownum-1)
WHERE RowNum = #rownum
Fetch Next from cbcursor into #rownum;
END;
Close cbcursor;
Deallocate cbcursor;
SELECT a,b,t2.RandoID, r.RandoName FROM #t3
LEFT OUTER JOIN #t2 t2 on t2.IDChild = #t3.c OR t2.IDChild = #t3.b OR t2.IDChild = #t3.a
LEFT OUTER JOIN #RandoName r on t2.RandoID = r.RandoID
This is what I get:
If you have any changes in your tables, like more records for T2, this script should be modified.
Using recursion:
declare #t table (IDc int , Idp int)
insert into #t
values
(321,null)
,(123,321)
,(124,123)
,(116,124)
declare #t2 table (RandoID varchar(10), IDChild int)
insert into #t2
values('asdf',123)
;with cte as
(
select anchor = IDChild
,ParentOrSelf = IDc
,RandoID
,RandomName
from #t
cross join (select RandoID,RandoName from #t2 t2 join #t3 t3 on t2.RandoID=t3.RandoID) crossed
where IDc=#anchor
union all
select t2.IDChild
,IDc
, t2.RandoID,RandomName
from #t t
cross join (select RandoID,RandoName from #t2 t2 join #t3 t3 on t2.RandoID=t3.RandoID) t2
join cte on cte.ParentOrSelf = t.Idp
)
select IDc
, cte.RandoID,cte.RandomName
from #t t
left join cte on t.IDc = cte.ParentOrSelf
Results:
IDc RandoID
321 NULL
123 asdf
124 asdf
116 asdf

Temporary table in where clause

I need some records from Temporary table and for this I am trying to run following query:
DECLARE #temp_table TABLE (Id uniqueidentifier, Dates nvarchar(10))
INSERT #temp_table
SELECT ID,Right(Companies.UserDefined4, 10)
FROM Companies
Select *
From Companies,#temp_table
Where Companies.ID = #temp_table.Id
But in Where clause I am getting this error:
The scalar variable #temp_table must be declared.
The correct code should be like :
DECLARE #temp_table TABLE (Id uniqueidentifier, Dates nvarchar(10))
INSERT #temp_table
SELECT ID,Right(Companies.UserDefined4, 10)
FROM Companies
Select *
From Companies c
join #temp_table t
on c.ID = t.Id
Try
SELECT *
FROM Companies c
INNER JOIN #temp_table t ON c.ID = t.ID

SQL select -one to many joins want to have the manys

I have two tables, TBL_PARENT (parentID, ParentName) and TBL_CHILDREN (ParentID,Child_Name)
A Parent can have 0 to many children
What I want is a query to give me a list of parent and their children in single row per parent.
For example
Parent1 John,Mary
Parent2 jane,steve,jana
And the number of rows to be the total number of parents
try this query :
I have created 3 table 2 of them are already created on your database #parant, #ch
and the third one is a temp table to put the result in.
create table #parant (id int , name varchar(10))
create table #ch (id int , name varchar(10), pid int)
insert into #parant select 1,'PA'
insert into #parant select 2,'PB'
insert into #parant select 3,'PC'
insert into #ch select 1,'Ca',1
insert into #ch select 1,'Cb',1
insert into #ch select 1,'Cc',1
insert into #ch select 1,'Cd',3
insert into #ch select 1,'Cf',3
insert into #ch select 1,'Ch',1
create table #testTable (id int, name varchar(10),chid int, chname varchar(10), cpid int)
insert into #testTable
select x.id , x.name ,isnull( y.id ,0), isnull(y.name,'') ,isnull(y.pid ,0)
from #parant as x
left outer join #ch as y
on x .id = y .pid
SELECT t.ID, t.name , STUFF(
(SELECT ',' + s.chname
FROM #TestTable s
WHERE s.ID = t.ID
FOR XML PATH('')),1,1,'') AS CSV
FROM #TestTable AS t
GROUP BY t.ID, t.name
GO
drop table #testTable
drop table #ch
drop table #parant
for the above data i got the following result
1 PA Ca,Cb,Cc,Ch
2 PB
3 PC Cd,Cf
SELECT COUNT(P.parentID),
P.ParentName,
C.Child_Name
FROM TBL_PARENT as P
INNER JOIN TBL_CHILDREN as C
WHERE P.parentID == c.ParentID
GROUP BY P.ParentName;
The line P.parentID == c.ParentID is doing the Join, and the line count(P.parentID) is doing the count of all the parents and the line GROUP BY P.ParentName is grouping all the rows by the name of the parent so you can display all the children of every single parent.

SQL intersect with other tables, how do I ignore it?

I am trying to run a query given three tables.
DECLARE #TABLE1 TABLE (ID CHAR(2))
DECLARE #TABLE2 TABLE (ID CHAR(2))
DECLARE #TABLE3 TABLE (ID CHAR(2))
INSERT INTO #TABLE1 VALUES('1')
INSERT INTO #TABLE1 VALUES('2')
INSERT INTO #TABLE2 VALUES('1')
--NOTHING in TABLE3
I Need to get only the values that are present and ignore the null table. This doesn't work since TABLE3 has no values.
SELECT ID
FROM #TABLE1
INTERSECT
SELECT ID
FROM #TABLE2
INTERSECT
SELECT ID
FROM #TABLE3
**Result should be 1**
How do I ignore the any table if it's null but keep the other values?
Why not do a union of select distincts from each table, and then group that by ID and select count(*), and select only rows with count(*) equal to the maximum value of count(*) in the result?
It's a bit of a mess of subqueries at this point unfortunately but you should get the logic :)
Intersect is not going to work for you as you can't add conditions to it.
From what I understand you want to select all records where the ID appears in at least 2 of the tables. I am assuming that the ID is unique to each table.
The following works in MS SQL Server:
DECLARE #TABLE1 TABLE (ID CHAR(2))
DECLARE #TABLE2 TABLE (ID CHAR(2))
DECLARE #TABLE3 TABLE (ID CHAR(2))
INSERT INTO #TABLE1 VALUES('1')
INSERT INTO #TABLE1 VALUES('2')
INSERT INTO #TABLE2 VALUES('1')
--NOTHING in TABLE3
;WITH AllValues AS
(
SELECT ID
FROM #TABLE1
UNION ALL
SELECT ID
FROM #TABLE2
UNION ALL
SELECT ID
FROM #TABLE3
)
SELECT ID
FROM AllValues
GROUP BY ID
HAVING COUNT(*) > 1
Maybe... But the design of the system is extremely foreign; a real world example would help understand what you're trying to do.
Select count(*), ID FROM (
Select ID from #table1
UNION
Select ID from #table2
UNION
Select ID from #table3) Derived
Where RowNum =1
GROUP BY ID
ORder by count(*) DESC
Updated where clause was in wrong place

how to copy some columns from deferent tables into another table using sql statement

I am very stressful with Sql coding. Any solution please help....
I have tables like below :
OrderedFood(**TableID,FoodID**,Qty,OrderedDate)
Invoices(**InvoiceID**,TableID,Amount)
InvoiceDetail(**InvoiceID,FoodID**,Qty,orderedDate)
I want to copy OrderedFood.TableID => Invoices.TableID. then copy OrderedFood.FoodID => InvoiceDetail.FoodID , OrderedFood.Qty => InvoiceDetail.Qty which this content a lot of rows.
How could i do it ?
Thanks in advance ...
I'm afraid it is a bit hard to understand exactly what you are trying to do.
Hopefully the following SQL can help point you in the right direction
DECLARE #OrderedFood Table(TableID int ,FoodID int ,Qty int ,OrderedDate datetime)
DECLARE #Invoices Table(InvoiceID int IDENTITY(1,1)PRIMARY KEY CLUSTERED, TableID int ,Amount money)
DECLARE #InvoiceDetail Table(InvoiceID int,FoodID int,Qty int ,orderedDate datetime)
insert into #orderedfood values(1,1,1,'2010/05/21')
insert into #orderedfood values(1,2,3,'2010/05/21')
insert into #orderedfood values(1,3,2,'2010/05/21')
insert into #orderedfood values(2,1,4,'2010/05/21')
insert into #orderedfood values(2,2,2,'2010/05/21')
insert into #Invoices(TableId) SELECT distinct TableId From #OrderedFood
Insert into #InvoiceDetail(InvoiceID,FoodID,Qty,orderedDate)
SELECT InvoiceID,FoodId,Qty,OrderedDate
FROM #OrderedFood o
inner join #Invoices i on o.tableid = i.tableid
select * from #invoices i inner join #invoicedetail id on i.invoiceid = id.invoiceid
You should use INSER INTO ....SELECT type query for example
INSERT INTO table1 ( column1 )
SELECT col1
FROM table2
other one is SELECT INTO Statement
SELECT column_name(s)
INTO new_table_name [IN externaldatabase]
FROM old_tablename