SQL Select Into #Temp - sql

I have a complex SQL query that works. It's like
SELECT * FROM Site s
JOIN (
SELECT DISTINCT z.Value FROM Doc z
JOIN (
SELECT x.DocumentID FROM Doc x
JOIN (
SELECT DocumentID, MAX(VERSION) AS VERSION
FROM Doc GROUP BY DocumentID) y ON y.DocumentID = x.DocumentID
WHERE DocumentTypeID = 78 AND MetadataTypeID = 22 AND VALUE > GETDATE() AND y.Version = x.Version
) a ON z.DocumentID = a.DocumentID
WHERE MetadataTypeID = 2
) b ON b.Value = s.SiteID
WHERE SiteID > 0
It does what I want it to do. But when I wrap it in
SELECT * INTO #Temp FROM ()
I get an incorrect syntax near ')'.
I'm confused. I just want to put the results into a temp table so I can do further work on it. Why doesn't it work?

You're missing an alias for subquery.
SELECT * INTO #MyTempTable
FROM
(
SELECT * FROM Site s
JOIN (
SELECT DISTINCT z.Value FROM Doc z
JOIN (
SELECT x.DocumentID FROM Doc x
JOIN (
SELECT DocumentID, MAX(VERSION) AS VERSION
FROM Doc GROUP BY DocumentID) y ON y.DocumentID = x.DocumentID
WHERE DocumentTypeID = 78 AND MetadataTypeID = 22 AND VALUE > GETDATE() AND y.Version = x.Version
) a ON z.DocumentID = a.DocumentID
WHERE MetadataTypeID = 2
) b ON b.Value = s.SiteID
WHERE SiteID > 0
) AS DT

select * into TBL_name from
( SELECT * FROM Site s
JOIN (
SELECT DISTINCT z.Value FROM Doc z
JOIN (
SELECT x.DocumentID FROM Doc x
JOIN (
SELECT DocumentID, MAX(VERSION) AS VERSION
FROM Doc GROUP BY DocumentID) y ON y.DocumentID = x.DocumentID
WHERE DocumentTypeID = 78 AND MetadataTypeID = 22 AND VALUE > GETDATE() AND y.Version = x.Version
) a ON z.DocumentID = a.DocumentID
WHERE MetadataTypeID = 2
) b ON b.Value = s.SiteID
WHERE SiteID > 0)al

Related

Change the SELECT in WHERE clause to another solution

I want to make my query better. What opportunities that I have to change this code for a faster one?
SELECT sn
FROM package p
WHERE StatusID = 1
AND ( NOT EXISTS( SELECT * FROM packagedetail pd
WHERE pd.packageID = p.ID AND packageDetailStatus = 12 )
OR ( EXISTS ( SELECT * FROM packagedetail pd
WHERE pd.packageID = p.ID AND packageDetailStatus = 12)
AND EXISTS ( SELECT * FROM unit u JOIN unitDetail ON u.ID = ud.unitID
WHERE (ud.InmostPackageID = p.ID OR ud.OutmostPackageID = p.ID)
AND u.UnitStateID in (8120, 8130, 8140)
)
)
)
( I know this is so ugly, but I want to know, how can I improve my skills )
One simplification that you can do is to not repeat the NOT EXISTS subquery again.
The below query is semantically equivalent to yours:
SELECT p.sn
FROM package p
WHERE p.StatusID = 1
AND (
NOT EXISTS(SELECT * FROM packagedetail pd
WHERE pd.packageID = p.ID AND packageDetailStatus = 12)
OR
EXISTS (SELECT * FROM unit u JOIN unitDetail ON u.ID = ud.unitID
WHERE (ud.InmostPackageID = p.ID OR ud.OutmostPackageID = p.ID) AND u.UnitStateID in (8120, 8130, 8140))
);
because:
(NOT X) OR (X AND Y) = (NOT X) OR Y
An alternative that might make it easier to read:
SELECT sn
FROM
package p
cross apply
(select
exists_packagedetail =case when exists (
SELECT *
FROM packagedetail pd
WHERE pd.packageID = p.ID AND packageDetailStatus = 12
) then 1 else 0 end
,exists_unitdetail =case when exists (
SELECT *
FROM
unit u
JOIN unitDetail ON u.ID = ud.unitID
WHERE (ud.InmostPackageID = p.ID OR ud.OutmostPackageID = p.ID) AND u.UnitStateID in (8120, 8130, 8140)
)then 1 else 0 end
) as q1
WHERE StatusID = 1 and (q1.exists_unitdetail=1 or q1.exists_packagedetail=0)

How can I optimize this SQL code further to run faster

UPDATE N SET [actType] = 'X'
FROM tableA N
WHERE NOT EXISTS (SELECT 1
FROM tableA O
WHERE O.clientCode = N.clientCode AND
O.[userName] = N.[userName] AND
O.[profile] = N.[profile] AND
O.[rankID] = N.[rankID] - 1
) AND
N.[rankID] NOT IN (SELECT MIN(T.[rankID])
FROM tableA T
WHERE T.[userName] = N.[userName]
)
You can use row_number() with updatable cte :
with cte as (
select N.*, ROW_NUMBER() OVER (PARTITION BY [userName] ORDER BY rankID) AS Seq
from tableA N
)
update c
set c.[actType] = 'X'
from cte c
where seq > 1 and
not exists (SELECT 1
FROM tableA O
WHERE O.clientCode = c.clientCode AND
O.[userName] = c.[userName] AND
O.[profile] = c.[profile] AND
O.[rankID] = c.[rankID] - 1
);
Your syntax suggests SQL Server. So, you can use.

Alternative solution for below SQL Query ,TableMasterID NOT IN take so much time

Need alternative solution for below SQL Query ,TableMasterID NOT IN take so much time, If i remove AND TableMasterID NOT IN
(SELECT DISTINCT c.TableMasterID
FROM ComFinalDataBS as C
WHERE C.ComFileID IN
(SELECT Number FROM fn_SplitInt(#ComFileID,','))) text from below query then getting result in 20 seconds otherwise result getting arround 4 minus.
SELECT A.SubTitleId,TableMasterID from SubTitle as A JOIN ComTableMaster as B ON a.SubTitle = b.TblName AND TableMasterID NOT IN (SELECT DISTINCT c.TableMasterID
FROM ComFinalDataBS as C
WHERE C.ComFileID IN
(SELECT Number FROM fn_SplitInt(#ComFileID,','))) AND B.TableMasterID IN
(SELECT DISTINCT d.TableMasterID
FROM ComData as D
WHERE D.ComFileID IN
(SELECT Number FROM fn_SplitInt(#ComFileID,','))) ORDER BY A.MainTitleID
SELECT A.SubTitleId ,
TableMasterID
FROM SubTitle AS A
JOIN ComTableMaster AS B ON A.SubTitle = B.TblName
WHERE NOT EXISTS ( SELECT 1
FROM ComFinalDataBS C
WHERE TableMasterID = C.TableMasterID
AND C.ComFileID IN (
SELECT Number
FROM MEFCampus..fn_SplitInt(#ComFileID, ',') ) )
AND NOT EXISTS ( SELECT 1
FROM ComData D
WHERE TableMasterID = D.TableMasterID
AND D.ComFileID IN (
SELECT Number
FROM MEFCampus..fn_SplitInt(#ComFileID,
',') ) )
AND B.IsDeleted = 0
ORDER BY MainTitleID
Have you tried storing the result from the fn_split_string() into an indexed temp-table first? It should help the Query Optimizer a lot.
SELECT DISTINCT Number
INTO #ComFileID
FROM dbo.fn_SplitInt(#ComFileID,',')
CREATE UNIQUE CLUSTERED INDEX uq0_ComFileID ON #ComFileID (Number) WITH (FILLFACTOR = 100)
SELECT A.SubTitleId,TableMasterID
FROM SubTitle as A
JOIN ComTableMaster as B
ON a.SubTitle = b.TblName
/*
AND B.TableMasterID NOT IN (SELECT DISTINCT c.TableMasterID
FROM ComFinalDataBS as C
JOIN #ComFileID CFI
ON CFI.Number = C.ComFileID )
*/
AND NOT EXISTS ( SELECT *
FROM ComFinalDataBS as C
JOIN #ComFileID CFI
ON CFI.Number = C.ComFileID
WHERE c.TableMasterID = B.TableMasterID )
/*
AND B.TableMasterID IN (SELECT DISTINCT d.TableMasterID
FROM ComData as D
JOIN #ComFileID CFI
ON CFI.Number = D.ComFileID
*/
AND EXISTS ( SELECT *
FROM ComData as D
JOIN #ComFileID CFI
ON CFI.Number = D.ComFileID
WHERE D.TableMasterID = B.TableMasterID )
ORDER BY A.MainTitleID

SQL join two simple query with count and groupby

hello i have 2 queries and i wanna join together but i don't know how...
SELECT *, count(*) as invii
FROM professionisti JOIN preventivi_invii ON
professionisti.email=preventivi_invii.email
GROUP BY professionisti.email
HAVING invii> 300
SELECT *, count(*) as acquisti
FROM professionisti JOIN contatti_acquistati ON
professionisti.email=contatti_acquistati.email
GROUP BY professionisti.email
HAVING acquisti> 5
the problem for me is multiple count and the group by with same column.
thank u
How about the below query. You would just change the WHERE clause to meet your needs.
SQL Fiddle Example:
SELECT * FROM
(
SELECT p.email,
CASE WHEN ISNULL(m1.invii) THEN 0 ELSE m1.invii END AS invii,
CASE WHEN ISNULL(m2.acquisti) THEN 0 ELSE m2.acquisti END AS acquisti
FROM professionisti p
LEFT JOIN
(
SELECT pp.email, COUNT(*) AS invii
FROM preventivi_invii pp
GROUP BY pp.email
) AS m1 ON p.email = m1.email
LEFT JOIN
(
SELECT c.email, COUNT(*) AS acquisti
FROM contatti_acquistati c
GROUP BY c.email
) AS m2 ON p.email = m2.email
) AS mm
WHERE mm.invii = 0
OR mm.acquisti = 0;
Or you could use:
SELECT * FROM
(
SELECT p.email,
(
SELECT
CASE WHEN ISNULL(COUNT(*)) THEN 0 ELSE COUNT(*) END
FROM preventivi_invii pp
WHERE pp.email = p.email
) AS invii,
(
SELECT
CASE WHEN ISNULL(COUNT(*)) THEN 0 ELSE COUNT(*) END
FROM contatti_acquistati c
WHERE c.email = p.email
) AS acquisti
FROM professionisti p
) AS mm
WHERE mm.invii = 0
OR mm.acquisti = 0

Update statement not compiling using alias

This is my update statement which is not being compiled:
Update Documents d
Set
DocumentDate = 1,
LastStatusChangedDateTime = (
Select Top 1 DATEADD(ss,1,StatusChangedDateTime)
From [dbo].[DocumentStatusesHistory] dsh
Where dsh.DocumentID = d.DocumentID
)
Where DocumentID In
(
Select Data From dbo.Split(#DocumentIDs,',')
)
I am unable to use d as an alias. How can I fix this?
How about this?
Update Documents
Set
DocumentDate = 1,
LastStatusChangedDateTime = (
Select Top 1 DATEADD(ss,1,StatusChangedDateTime)
From [dbo].[DocumentStatusesHistory] dsh
Where dsh.DocumentID = d.DocumentID
)
From Documents d
Where DocumentID In
(
Select Data From dbo.Split(#DocumentIDs,',')
)
Add FROM clause:
Update d
Set
DocumentDate = 1,
LastStatusChangedDateTime = (
Select Top 1 DATEADD(ss,1,StatusChangedDateTime)
From [dbo].[DocumentStatusesHistory] dsh
Where dsh.DocumentID = d.DocumentID
)
FROM Documents AS d
...
Try this one :
UPDATE d
SET d.DocumentDate = 1 ,
d.LastStatusChangedDateTime = ( SELECT TOP 1
DATEADD(ss, 1,
StatusChangedDateTime)
FROM [dbo].[DocumentStatusesHistory] dsh
WHERE dsh.DocumentID = d.DocumentID
)
FROM Documents d
WHERE d.DocumentID IN ( SELECT Data
FROM dbo.Split(#DocumentIDs, ',') )