Can't put a second "with" statement into the query - sql

I have a query - which is combining with a Union statement the 5 columns into 2 columns.
So basically - an ID + Some Information. As the ID could be in column 2-5 - several times... I rearranged to be everything in one ID column + the text.
Now - I wanted to use a second "with" statement - to combine the IDs of several rows - with a XML path. But here I got stuck.
That is the code - which gives me the two column - with content as expected:
With
STall as (Select
'Status: ' + ST.Status + Char(10) + 'Crew Information:' + Char(10) +
'Instructor: ' + ST.IP + Char(10) + 'Student: ' + ST.SP + Char(10) + Case
When ST.ACM1 = 'NA' Then '' Else 'ACM1: ' + ST.ACM1 + Char(10) End + Case
When ST.ACM2 = 'NA' Then '' Else 'ACM2: ' + ST.ACM2 + Char(10)
End + 'Lesson: ' + ST.Lesson + Char(10) + Case
When ST.ScheduleRemarks = '' Then ''
Else ' REM:' + ST.ScheduleRemarks + Char(10)
End + 'Equipment: ' + ST.EquipmentName + ' (' + ST.Callsign + ')' +
Char(10) + 'Start: ' + Convert(VARCHAR(10),ST.ScheduleTO,104) + ' - ' +
Convert(VARCHAR(5),ST.ScheduleTO,108) + ' UTC' + Char(10) + 'End: ' +
Convert(VARCHAR(10),ST.ScheduleTD,104) + ' - ' +
Convert(VARCHAR(5),ST.ScheduleTD,108) + ' UTC' + Char(10) + Case
When ST.ATC = 'NA' Then '' Else ST.ATC End As SInfo,
ST.IDIP,
ST.IDSP,
ST.IDA1,
ST.IDA2
From
(Select
Case When Schedule.StatusRelease = 1 Then 'OK' Else Case
When Schedule.StatusRequest = 1 Then 'STBY' Else 'N/A' End
End As Status,
Schedule.ContactIDIP,
Schedule.ContactIDSP,
MasterLesson.Lesson,
Equipment.EquipmentName,
CallSignList.Callsign,
Schedule.Meeting,
Schedule.ScheduleRemarks,
Schedule.StatusRelease,
Schedule.StatusRequest,
Schedule.ScheduleDay,
ContactList.FullNameTLC As IP,
ContactList1.FullNameTLC As SP,
Case When Schedule.ContactIDACM1 = 0 Then 'NA'
Else ContactList2.FullNameTLC End As ACM1,
Case When Schedule.ContactIDACM2 = 0 Then 'NA'
Else ContactList3.FullNameTLC End As ACM2,
Schedule.ScheduleTO,
Schedule.ScheduleTD,
Case When Schedule.RouteID = 0 Then 'NA'
Else 'Route: ' + Airport.ICAO + ' - ' + Case
When IsNull(Airport1.ICAO, 'NA') = 'NA' Then ' '
Else Airport1.ICAO + ' - ' End + Airport2.ICAO + Char(10) + Char(13)
End As ATC,
ContactList.Id As IDIP,
ContactList1.Id As IDSP,
ContactList2.Id As IDA1,
ContactList3.Id As IDA2
From
Schedule Inner Join
StudentLesson On Schedule.ScheduleLessonID = StudentLesson.StudentLessonID
Inner Join
MasterLesson On StudentLesson.LessonID = MasterLesson.ID Inner Join
Equipment On Schedule.EquipmentID = Equipment.ID Left Join
CallSignList On CallSignList.ID = Schedule.CallSignListID Left Join
Route On Route.ID = Schedule.RouteID Inner Join
ContactList On ContactList.Id = Schedule.ContactIDIP Inner Join
ContactList ContactList1 On ContactList1.Id = Schedule.ContactIDSP
Left Join
ContactList ContactList2 On Schedule.ContactIDACM1 = ContactList2.Id
Left Join
ContactList ContactList3 On Schedule.ContactIDACM2 = ContactList3.Id
Left Join
Airport On Route.AirportID_Dep = Airport.ID Left Join
Airport Airport1 On Route.AirportID_Via = Airport1.ID Left Join
Airport Airport2 On Route.AirportID_Arr = Airport2.ID
Where
((Schedule.StatusRelease = 1) Or
(Schedule.StatusRequest = 1)) And
Schedule.ScheduleDay = '21.02.2014') As ST)
Select Distinct
STall.IDIP,SInfo
From
STall
where STall.IDIP > 0
UNION
Select Distinct
STall.IDSP,SInfo
From
STall
where STall.IDSP > 0
UNION
Select Distinct
STall.IDA1,SInfo
From
STall
where STall.IDA1 > 0
UNION
Select Distinct
STall.IDA2,SInfo
From
STall
where STall.IDA2 > 0
Now - I tried to add another With STtotal as ( in the beginning...
and
)
Select Distinct
STsub.IDIP,
SubString((Select
+Char(10) + STn1.SInfo As [text()]
From
STsub STn1
Where
STn1.IDIP = STtotal.IDIP
Order By
STn1.IDIP
For Xml Path('')), 2, 1000) ScheduleInfo
From
STtotal
But I get an error - with wrong Statement at "with".
Maybe there is another approach - how to combine - the "Info Text" column with all IDs - which could be in column 2-5.
Thanks for any imput

Separate your CTEs with a comma; the WITH only needs to be specified once:
;WITH CTE1 AS (
...
), CTE2 AS (
...
)
SELECT ...

Did you remember to put a semi colon at the end of the first statement?

Related

How to compare data from multiple databases

I'm trying to compare some data from different multiple databases, as I have illustrate my current case, I have there databases, database 1 is the main, and time to time database 2 and database 3 are updated from database 1. I have some difficulties to get the final result which return the data from database 1 and two columns column show the availability in database 2 as Yes or No, and the same with second extra column that will indicate the data availability on the database 3 with Yes or NO.
SELECT *
FROM (
Select ID as db1_ID,
First_name as db1_First_name,
Last_name as db1_Last_name,
Email as db1_Email,
Password as db1_Password,
Request_Id as db1_Request_Id,
User_Id as db1_User_Id,
Request_name as db1_Request_name
from User
inner join User_request
on User_request.User_Id = user.ID
) AS DB1_VIEW
LEFT OUTER JOIN
(
Select ID as db2_ID,
First_name as db2_First_name,
Last_name as db2_Last_name,
Email as db2_Email,
Password as db2_Password,
Request_Id as db2_Request_Id,
User_Id as db2_User_Id,
Request_name as db2_Request_name
from User
inner join User_request
on User_request.User_Id = user.ID
) AS DB2_VIEW
ON db2_ID = db1_ID
LEFT OUTER JOIN
(
Select ID as db3_ID,
First_name as db3_First_name,
Last_name as db3_Last_name,
Email as db3_Email,
Password as db3_Password,
Request_Id as db3_Request_Id,
User_Id as db3_User_Id,
Request_name as db3_Request_name
from User
inner join User_request
on User_request.User_Id = user.ID
) AS DB3_VIEW
ON db3_ID = db1_ID
ID First_name Last_name Email Password Request_Id User_Id Request_name
1 Oliver Jake OJake#domain.com 123 1 1 Request1
2 Mathew Harry MHarry#domain.com 123 1 2 Request1
3 Jacob Reece JReece#domain.com 123 1 3
Request1
4 Charlie Damian CDamian#domain.com 123 1 4 Request1
Use this as your first select statement:
SELECT DB1_VIEW.*
,CASE WHEN DB2_VIEW.db2_ID IS NOT NULL THEN 'Y' ELSE 'N' END AS Available_db2
,CASE WHEN DB3_VIEW.db3_ID IS NOT NULL THEN 'Y' ELSE 'N' END AS Available_db3
You can remove all the details apart from the ID fields in the db2_view and db3_view subqueries.
You can use the below query before execute you should use replace [SourceDB] to your source database and [TargertDB] to your target database. Insert the table name into #mdtables to include for comparison.
USE [SourceDB]
IF Object_id('tempdb..#mdTables') IS NOT NULL
DROP TABLE #mdtables;
CREATE TABLE #mdtables
(
id INT IDENTITY(1, 1) NOT NULL,
schemaname NVARCHAR(128),
tablename NVARCHAR(128)
);
INSERT INTO #mdtables
(schemaname,
tablename)
VALUES ('dbo',
'user');
DECLARE #mdTableLim INT =0,
#mdTableRowId INT =0
SELECT #mdTableLim = Count(*)
FROM #mdtables;
SET #mdTableRowId = 1;
WHILE #mdTableRowId <= #mdTableLim
BEGIN
DECLARE #SDBName VARCHAR(50) = '[SourceDB]',
#TDBName VARCHAR(50) = '[TargertDB]',
#tableName VARCHAR(100) = ''
DECLARE #WhereF VARCHAR(max) ='',
#joincondition VARCHAR(max) ='',
#or VARCHAR(10) ='',
#select VARCHAR(max) = '',
#comma VARCHAR(1)='',
#query VARCHAR(max) ='',
#and VARCHAR(5)='',
#where1 VARCHAR(1000) ='',
#wOR VARCHAR(5)=''
SELECT #tableName = tablename
FROM #mdtables
WHERE id = #mdTableRowId;
SELECT #joincondition += Isnull(#and + ( CASE
WHEN cu.column_name IS NULL
THEN
NULL
ELSE ' src.[' + cu.column_name
+
'] = ' +
'trgt.['
+ c.column_name + ']'
END ), ''),
#WhereF += Isnull (#or + ( CASE
WHEN cu.column_name IS NOT NULL THEN
NULL
ELSE Isnull ( ' src.[' +
TC.column_name
+
'] ',
' isnull( src.[' +
C.column_name +
'],1) ' )
+ Isnull( '<> trgt.[' +
TC.column_name
+ ']',
' = isnull (src.['
+
C.column_name + '],1) ')
END ), ''),
#or = ( CASE
WHEN cu.column_name IS NOT NULL THEN ''
ELSE ' OR '
END ),
#and = ( CASE
WHEN cu.column_name IS NULL THEN ''
ELSE ' AND '
END ),
#select += #comma + ' src.[' + c.column_name + '] '
+ Isnull (' , trgt.[' + TC.column_name + ']', ''),
#comma = ',',
#where1 += Isnull(( #wOR + ( CASE
WHEN cu.column_name IS NULL THEN
NULL
ELSE ' trgt.[' + cu.column_name +
'] is null '
END ) ), ''),
#wOR = ( CASE
WHEN cu.column_name IS NULL THEN ''
ELSE ' OR '
END )
FROM information_schema.columns C
LEFT JOIN information_schema.key_column_usage CU
ON C.column_name = cu.column_name
AND constraint_name LIKE 'PK_%'
AND c.table_name = cu.table_name
LEFT JOIN [TargertDB].information_schema.columns TC
ON C.column_name = TC.column_name
AND c.table_name = TC.table_name
WHERE c.table_name = #tableName
--AND columnproperty(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 0
AND c.column_name NOT IN ( 'LST_CHG_TMS', 'LST_CHG_TMS',
'LST_CHG_USR_ID'
,
'LST_CHG_USR_ID' )
AND c.data_type NOT IN ( 'image' )
ORDER BY cu.column_name
SET #query = 'select ' + #select + ' from ' + #SDBName + '.dbo.'
+ #tableName + ' as src left join ' + #TDBName
+ '.dbo.' + #tableName + ' as trgt on '
+ #joincondition + ' where (' + #where1 + ')'
+ Isnull ('and '+ NULLIF (#WhereF, ''), '')
DECLARE #qu1 VARCHAR(max) =
' declare #cnt int =0 select #cnt =count (1) from '
+ #SDBName + '.dbo.' + #tableName
+ ' as src left join ' + #TDBName + '.dbo.'
+ #tableName + ' as trgt on ' + #joincondition
+ ' where (' + #where1 + ')'
+ Isnull (' OR '+ NULLIF (#WhereF, ''), '')
+ ' if (#cnt>0) begin select '''
+ #tableName + ''' as [ ],#cnt ' +-- #query + ' end '
BEGIN try
EXECUTE ( #qu1)
END try
BEGIN catch
PRINT #qu1;
END catch
SET #mdTableRowId = #mdTableRowId + 1
END
This might not need CTE's or sub-queries.
A few joins might do it.
SELECT
Usr1.ID AS db1_User_Id,
Usr1.First_name AS db1_First_name,
Usr1.Last_name AS db1_Last_name,
Usr1.Email AS db1_Email,
Usr1.Password AS db1_Password,
MAX(UsrReq1.Request_Id) AS db1_Request_Id,
MAX(UsrReq1.Request_name) AS db1_Request_name,
CASE WHEN COUNT(UsrReq2.User_Id) > 0 THEN 'Y' ELSE 'N' END AS Available_Db2,
CASE WHEN COUNT(UsrReq3.User_Id) > 0 THEN 'Y' ELSE 'N' END AS Available_Db3
FROM [Database1].[User] AS Usr1
LEFT JOIN [Database1].[User_request] AS UsrReq1 ON UsrReq1.User_Id = Usr1.ID
LEFT JOIN [Database2].[User] AS Usr2 ON Usr2.ID = Usr1.ID
LEFT JOIN [Database2].[User_request] AS UsrReq2 ON UsrReq2.User_Id = Usr2.ID
LEFT JOIN [Database3].[User] AS Usr3 ON Usr3.ID = Usr1.ID
LEFT JOIN [Database3].[User_request] AS UsrReq3 ON UsrReq3.User_Id = Usr3.ID
GROUP BY
Usr1.ID,
Usr1.First_name,
Usr1.Last_name,
Usr1.Email,
Usr1.Password;

Return newest row when several columns are the same

I have a very complex Union query that returns up to two rows. If the second through the 15th columns are identical in both records, I want to return the results of the second record. Otherwise, return the results of the first record which is the newest record. The goal is to return the newest name and address with a pending flag only if the data is not the same.
SELECT TOP 1
1 AS updatePending,
a.entity_number,
a.name_title,
a.name_first,
a.name_middle,
a.name_last,
a.name_suffix,
LTRIM(RTRIM(REPLACE(
LTRIM(RTRIM(ISNULL(a.name_first, ''))) +
CASE WHEN LEN(LTRIM(RTRIM(ISNULL(a.name_first, '')))) = 1 THEN '. ' ELSE ' ' END +
LTRIM(RTRIM(ISNULL(a.name_middle, ''))) +
CASE WHEN LEN(LTRIM(RTRIM(ISNULL(a.name_middle, '')))) = 1 THEN '. ' ELSE ' ' END +
LTRIM(RTRIM(ISNULL(a.name_last, ''))) + ' ' +
LTRIM(RTRIM(ISNULL(a.name_suffix, '')))
,' ',' '))) AS name_full,
NULLIF(LTRIM(RTRIM(
LTRIM(RTRIM(ISNULL(a.company, ''))) +
LTRIM(RTRIM(ISNULL(a.firm_name, ''))))),'') AS company,
a.address1,
a.mailing_address,
a.city,
a.state,
a.zip_code AS zipcode,
a.internet_address AS email_address,
a.time_stamp
FROM statebar.dbo.STAGING_Address_Change_Request a
INNER JOIN Member m ON m.entity_number = a.entity_number
WHERE a.entity_number = (
SELECT m.entity_number
FROM Member m
INNER JOIN Named_Entity ne ON (ne.entity_number = m.entity_number)
WHERE ne.name_last = 'Park'
AND m.birth_year = '1958'
AND m.barno = '12345'
)
AND a.time_stamp > m.time_stamp
UNION ALL
SELECT TOP 1
0 AS updatePending,
ne.entity_number,
ne.name_title,
ne.name_first,
ne.name_middle,
ne.name_last,
ISNULL(ne.name_suffix, ''),
LTRIM(RTRIM(REPLACE(
LTRIM(RTRIM(ISNULL(ne.name_first, ''))) +
CASE WHEN LEN(LTRIM(RTRIM(ISNULL(ne.name_first, '')))) = 1 THEN '. ' ELSE ' ' END +
LTRIM(RTRIM(ISNULL(ne.name_middle, ''))) +
CASE WHEN LEN(LTRIM(RTRIM(ISNULL(ne.name_middle, '')))) = 1 THEN '. ' ELSE ' ' END +
LTRIM(RTRIM(ISNULL(ne.name_last, ''))) + ' ' +
LTRIM(RTRIM(ISNULL(ne.name_suffix, '')))
,' ',' '))) AS name_full,
NULLIF(LTRIM(RTRIM(
LTRIM(RTRIM(ISNULL(ne.company, ''))) +
LTRIM(RTRIM(ISNULL(ne.firm_name, ''))))),'') AS company,
ISNULL(ne.address1, ''),
ne.mailing_address,
ne.city,
ne.state,
ne.zip_code,
ne.internet_address AS email_address,
m.time_stamp
FROM Member m
INNER JOIN Named_Entity ne ON (ne.entity_number = m.entity_number)
LEFT JOIN statebar.dbo.STAGING_Address_Change_Request a ON a.entity_number = m.entity_number
WHERE ne.entity_number = (
SELECT m.entity_number
FROM Member m
INNER JOIN Named_Entity ne ON (ne.entity_number = m.entity_number)
WHERE ne.name_last = 'Park'
AND m.birth_year = '1958'
AND m.barno = '12345'
)
AND m.time_stamp > a.time_stamp
ORDER BY updatePending DESC, a.time_stamp DESC

SQL Server stored proc substitute an empty string if column is empty or null

I need to check to see if a certain coloumn in my stored proc is either empty or null.
This is a snippet of what I have right now:
SELECT * ,
CASE WHEN a.USER IS NULL
THEN b.ROLE
ELSE ISNULL(a.FirstName,'') + ' ' + (ISNULL(a.MiddleName+' ','') + ISNULL(a.LastName,'')
END AS 'CustomerName'
I am checking to see if a.MiddleName is NULL but how do I also check to see if its empty and if its empty to just insert a empty string (no space)?
Thanks
Change to
SELECT
* ,
CASE
WHEN a.USER IS NULL
THEN b.ROLE
ELSE CASE
WHEN ISNULL(a.MiddleName, '') = ''
THEN ISNULL(a.FirstName,'') + ' ' + ISNULL(a.LastName,'')
ELSE ISNULL(a.FirstName,'') + ' ' + a.MiddleName + ' ' + ISNULL(a.LastName,'')
END
END AS 'CustomerName'
Another sollution is:
SELECT * ,
CASE WHEN a.USER IS NULL
THEN b.ROLE
ELSE ISNULL(a.FirstName,'') + replace( ( ' ' + ISNULL(a.MiddleName+' ',' '),' ',' ') + ISNULL(a.LastName,'')
END AS 'CustomerName'

using sql - Is not null in a select statement

I can't seem to figure out how to use the opposite of isnull or ifnull statements in sql. I need to say if a.Error1 is not null -- then print the ' - ' and the + CHAR(13)+CHAR(10). Basically There should be no dash or no new line break if the a.Error1 comes back null. So print the information if the field isn't null.
select a. ....
' - ' + a.Error1 + CHAR(13)+CHAR(10) +
' - ' + a.Error2 + CHAR(13)+CHAR(10) +
' - ' + a.Error3 + CHAR(13)+CHAR(10) +
' - ' + a.Error4 + CHAR(13)+CHAR(10) +
' - ' + a.Error5 + CHAR(13)+CHAR(10) +
' - ' + a.Error6 as 'error_message'
...
from table1 a
For example if for a given record error1, 2 and 5 returned output I would like the output to be as follows:
- Error1: There was a ...
- Error2: ....
- Error5: The data was ...
If no errors existed for that row it should simply be an empty/null field.
You can use CASE:
SELECT a. ....
(CASE WHEN a.Error1 IS NOT NULL
THEN ' - ' + a.Error1 + CHAR(13)+CHAR(10)
ELSE ''
END) +
(CASE WHEN a.Error2 IS NOT NULL
THEN ' - ' + a.Error2 + CHAR(13)+CHAR(10)
ELSE ''
END) +
(CASE WHEN a.Error3 IS NOT NULL
THEN ' - ' + a.Error3 + CHAR(13)+CHAR(10)
ELSE ''
END) +
...etc
Yes! i know i'm like 5 years too late but i too enountered this problem.
It's weird how it doesn't exist some kind of !ISNULL() but whatever.
Try this for a cleaner code:
select a. ....
IIF(a.Error1 IS NOT NULL, ' - ' + a.Error1 + CHAR(13)+CHAR(10) , '') as Error1,
IIF(a.Error1 IS NOT NULL, ' - ' + a.Error1 + CHAR(13)+CHAR(10) , '') as Error2
from table1 a
Learn more about IIF() function : SQL Server IIF Function
The COALESCE function does what you want here. The result of COALESCE is the first NOT NULL value it is passed. Below we use '', which is distinct from NULL so that the outer + is always applied to NOT NULL strings.
e.g.
select a. ....
COALESCE( ' - ' + a.Error1 + CHAR(13)+CHAR(10), '' ) +
COALESCE( ' - ' + a.Error2 + CHAR(13)+CHAR(10), '' ) +
COALESCE( ' - ' + a.Error3 + CHAR(13)+CHAR(10), '' ) +
COALESCE( ' - ' + a.Error4 + CHAR(13)+CHAR(10), '' ) +
COALESCE( ' - ' + a.Error5 + CHAR(13)+CHAR(10), '' ) +
COALESCE( ' - ' + a.Error6 , '' ) as 'error_message'
...
from table1 a
SELECT (CASE WHEN a.Error1 IS NOT NULL
THEN ' - ' + a.Error1 + CHAR(13)+CHAR(10) +
ELSE a.Error1
END) +
(CASE WHEN a.Error2 IS NOT NULL
THEN ' - ' + a.Error2 + CHAR(13)+CHAR(10) +
ELSE a.Error2
END) +
.....etc

How to improve SQL view with many joins

I'm quite new to SQL, I needed to create a data source which includes data from many different tables. I wrote following script. It works for low amount of data but when data size improves,it becomes impossible to get the data via this query. How can i improve this script, what might be the possible bottlenecks and keypoints ? Thanks in advance.
SELECT
dbo.IDW_COSTDETAIL.IDW_PROJECT_FK, dbo.IDW_PROJECT_DATA.CODE + ' - ' +
dbo.IDW_PROJECT_DATA.DESCRIPTION AS PROJECT,
dbo.IDW_PROJECT_ALTERNATIVE.CODE + ' - ' + dbo.IDW_PROJECT_ALTERNATIVE.DESCRIPTION AS PRJ_ALTERNATIVE,
dbo.IDW_COSTDETAIL.BOQ_NO,
dbo.IDW_COSTDETAIL.IDW_CONTROLLING_CODE_FK AS BUDGETCODE,
dbo.IDW_CONTROLLING_CODE.DESCRIPTION AS BC_DESCR,
dbo.IDW_ACTIVITY.CODE AS ACTIVITY_ID,
dbo.IDW_ACTIVITY.DESCRIPTION AS ACTIVITY_DESCR, dbo.IDW_BOQ_DETAIL.REFERENCE,
dbo.IDW_BOQ_DETAIL.OUTLINE_SPEC1, dbo.IDW_BOQ_DETAIL.UOM AS ITEM_UOM,
dbo.IDW_COSTDETAIL.COST_CODE,
dbo.IDW_COSTDETAIL.COMMODITY_CODE,
CASE
WHEN IDW_COSTDETAIL.COMMODITY_CODE IS NULL
THEN IDW_COST_CODE.DESCRIPTION
ELSE IDW_COMMODITIES.DESCRIPTION
END AS SUBITEM_DESCR,
dbo.IDW_BOQ_DETAIL.AQ_QUANTITY / (DATEDIFF(day, dbo.IDW_ACTIVITY.START_DATE, dbo.IDW_ACTIVITY.END_DATE) + 1) AS ITEM_AQ,
dbo.IDW_COSTDETAIL.QUANTITY_BASED_AQ / (DATEDIFF(day, dbo.IDW_ACTIVITY.START_DATE, dbo.IDW_ACTIVITY.END_DATE) + 1) AS SUBITEM_AQ,
CASE
WHEN IDW_COSTDETAIL.COMMODITY_CODE IS NULL
THEN IDW_COST_CODE.UOM
ELSE IDW_COMMODITIES.UOM
END AS SUBITEM_UOM,
dbo.IDW_COSTDETAIL.COST / (DATEDIFF(day, dbo.IDW_ACTIVITY.START_DATE, dbo.IDW_ACTIVITY.END_DATE) + 1) AS UNIT_COST,
CASE
WHEN IDW_COSTDETAIL.COMMODITY_CODE IS NULL
THEN IDW_COST_CODE.CURRENCY
ELSE IDW_COMMODITIES.ESTIMATE_CURRENCY
END AS CATALOG_CUR,
dbo.IDW_BOQ_DETAIL.IQ_QUANTITY / (DATEDIFF(day, dbo.IDW_ACTIVITY.START_DATE, dbo.IDW_ACTIVITY.END_DATE) + 1) AS ITEM_IQ,
dbo.IDW_COSTDETAIL_IQ.QUANTITY / (DATEDIFF(day, dbo.IDW_ACTIVITY.START_DATE, dbo.IDW_ACTIVITY.END_DATE) + 1) AS SUBITEM_IQ,
dbo.IDW_ACTIVITY.START_DATE, dbo.IDW_ACTIVITY.END_DATE, DATEDIFF(day, dbo.IDW_ACTIVITY.START_DATE, dbo.IDW_ACTIVITY.END_DATE) AS DURATION,
dbo.SQLCALENDAR.DateKey AS FULLDATE,
dbo.IDW_COST_CODE_HIER_V.CODE + ' - ' + dbo.IDW_COST_CODE_HIER_V.DESCRIPTION AS CODE,
dbo.IDW_COST_CODE_HIER_V.COC_LVL1 + ' - ' + dbo.IDW_COST_CODE_HIER_V.COC_DESC_LVL1 AS COC_LVL1,
dbo.IDW_COST_CODE_HIER_V.COC_LVL2 + ' - ' + dbo.IDW_COST_CODE_HIER_V.COC_DESC_LVL2 AS COC_LVL2,
dbo.IDW_COST_CODE_HIER_V.COC_LVL3 + ' - ' + dbo.IDW_COST_CODE_HIER_V.COC_DESC_LVL3 AS COC_LVL3,
dbo.IDW_COST_CODE_HIER_V.COC_LVL4 + ' - ' + dbo.IDW_COST_CODE_HIER_V.COC_DESC_LVL4 AS COC_LVL4,
dbo.IDW_COST_CODE_HIER_V.COC_LVL5 + ' - ' + dbo.IDW_COST_CODE_HIER_V.COC_DESC_LVL5 AS COC_LVL5,
dbo.IDW_COMMODITIES_HIER_V.CODE + ' - ' + dbo.IDW_COMMODITIES_HIER_V.DESCRIPTION AS COMMODITY,
dbo.IDW_COMMODITIES_HIER_V.COM_LVL1 + ' - ' + dbo.IDW_COMMODITIES_HIER_V.COM_DESC_LVL1 AS COM_LVL1, dbo.IDW_COMMODITIES_HIER_V.COM_LVL2 + ' - ' + dbo.IDW_COMMODITIES_HIER_V.COM_DESC_LVL2 AS COM_LVL2,
dbo.IDW_COMMODITIES_HIER_V.COM_LVL3 + ' - ' + dbo.IDW_COMMODITIES_HIER_V.COM_DESC_LVL3 AS COM_LVL3, dbo.IDW_COMMODITIES_HIER_V.COM_LVL4 + ' - ' + dbo.IDW_COMMODITIES_HIER_V.COM_DESC_LVL4 AS COM_LVL4,
dbo.IDW_COMMODITIES_HIER_V.COM_LVL5 + ' - ' + dbo.IDW_COMMODITIES_HIER_V.COM_DESC_LVL5 AS COM_LVL5
FROM
dbo.IDW_PROJECT_DATA
INNER JOIN
dbo.IDW_ACTIVITY
INNER JOIN
dbo.IDW_COSTDETAIL ON dbo.IDW_ACTIVITY.IDW_PROJECT_FK = dbo.IDW_COSTDETAIL.IDW_PROJECT_FK AND dbo.IDW_ACTIVITY.IDW_PROJECT_ALTERNATIVE_FK = dbo.IDW_COSTDETAIL.IDW_PROJECT_ALTERNATIVE_FK AND dbo.IDW_ACTIVITY.CODE = dbo.IDW_COSTDETAIL.IDW_ACTIVITY_FK
INNER JOIN
dbo.IDW_CONTROLLING_CODE ON dbo.IDW_COSTDETAIL.IDW_CONTROLLING_CODE_FK = dbo.IDW_CONTROLLING_CODE.CODE AND dbo.IDW_COSTDETAIL.IDW_PROJECT_ALTERNATIVE_FK = dbo.IDW_CONTROLLING_CODE.IDW_PROJECT_ALTERNATIVE_FK AND dbo.IDW_COSTDETAIL.IDW_PROJECT_FK = dbo.IDW_CONTROLLING_CODE.IDW_PROJECT_FK ON dbo.IDW_PROJECT_DATA.IDW_PROJECT_FK = dbo.IDW_ACTIVITY.IDW_PROJECT_FK
INNER JOIN
dbo.IDW_PROJECT_ALTERNATIVE ON dbo.IDW_PROJECT_DATA.IDW_PROJECT_FK = dbo.IDW_PROJECT_ALTERNATIVE.IDW_PROJECT_FK AND dbo.IDW_ACTIVITY.IDW_PROJECT_FK = dbo.IDW_PROJECT_ALTERNATIVE.IDW_PROJECT_FK AND dbo.IDW_ACTIVITY.IDW_PROJECT_ALTERNATIVE_FK = dbo.IDW_PROJECT_ALTERNATIVE.CODE AND dbo.IDW_COSTDETAIL.IDW_PROJECT_FK = dbo.IDW_PROJECT_ALTERNATIVE.IDW_PROJECT_FK AND dbo.IDW_COSTDETAIL.IDW_PROJECT_ALTERNATIVE_FK = dbo.IDW_PROJECT_ALTERNATIVE.CODE AND dbo.IDW_CONTROLLING_CODE.IDW_PROJECT_FK = dbo.IDW_PROJECT_ALTERNATIVE.IDW_PROJECT_FK AND dbo.IDW_CONTROLLING_CODE.IDW_PROJECT_ALTERNATIVE_FK = dbo.IDW_PROJECT_ALTERNATIVE.CODE
RIGHT OUTER JOIN
dbo.IDW_BOQ_DETAIL ON dbo.IDW_PROJECT_ALTERNATIVE.CODE = dbo.IDW_BOQ_DETAIL.IDW_PROJECT_ALTERNATIVE_FK AND dbo.IDW_PROJECT_ALTERNATIVE.IDW_PROJECT_FK = dbo.IDW_BOQ_DETAIL.IDW_PROJECT_FK AND dbo.IDW_COSTDETAIL.ITEM_REFERENCE = dbo.IDW_BOQ_DETAIL.REFERENCE AND dbo.IDW_COSTDETAIL.BOQ_NO = dbo.IDW_BOQ_DETAIL.IDW_BOQ_FK AND dbo.IDW_COSTDETAIL.IDW_PROJECT_FK = dbo.IDW_BOQ_DETAIL.IDW_PROJECT_FK
LEFT OUTER JOIN
dbo.IDW_COST_CODE ON dbo.IDW_PROJECT_DATA.IDW_PROJECT_FK = dbo.IDW_COST_CODE.IDW_PROJECT_FK AND dbo.IDW_COSTDETAIL.IDW_PROJECT_FK = dbo.IDW_COST_CODE.IDW_PROJECT_FK AND dbo.IDW_COSTDETAIL.COST_CODE = dbo.IDW_COST_CODE.CODE
LEFT OUTER JOIN
dbo.IDW_COMMODITIES ON dbo.IDW_PROJECT_DATA.IDW_PROJECT_FK = dbo.IDW_COMMODITIES.IDW_PROJECT_FK AND dbo.IDW_COSTDETAIL.IDW_PROJECT_FK = dbo.IDW_COMMODITIES.IDW_PROJECT_FK AND dbo.IDW_COSTDETAIL.COMMODITY_CODE = dbo.IDW_COMMODITIES.CODE
LEFT OUTER JOIN
dbo.IDW_COST_CODE_HIER_V ON dbo.IDW_COSTDETAIL.COST_CODE = dbo.IDW_COST_CODE_HIER_V.CODE AND dbo.IDW_COSTDETAIL.IDW_PROJECT_FK = dbo.IDW_COST_CODE_HIER_V.IDW_PROJECT_FK
LEFT OUTER JOIN
dbo.IDW_COMMODITIES_HIER_V ON dbo.IDW_COSTDETAIL.COMMODITY_CODE = dbo.IDW_COMMODITIES_HIER_V.CODE AND dbo.IDW_COSTDETAIL.IDW_PROJECT_FK = dbo.IDW_COMMODITIES_HIER_V.IDW_PROJECT_FK
LEFT OUTER JOIN
dbo.IDW_COSTDETAIL_IQ ON dbo.IDW_COSTDETAIL.IDW_PROJECT_FK = dbo.IDW_COSTDETAIL_IQ.IDW_PROJECT_FK AND dbo.IDW_COSTDETAIL.IDW_PROJECT_ALTERNATIVE_FK = dbo.IDW_COSTDETAIL_IQ.IDW_PROJECT_ALTERNATIVE_FK AND dbo.IDW_COSTDETAIL.ID = dbo.IDW_COSTDETAIL_IQ.IDW_COSTDETAIL_FK
CROSS JOIN
dbo.SQLCALENDAR
WHERE
(dbo.IDW_BOQ_DETAIL.ITEM_KIND = 2)
AND (dbo.SQLCALENDAR.DateKey BETWEEN CONVERT(CHAR(8), dbo.IDW_ACTIVITY.START_DATE, 112) AND CONVERT(CHAR(8), dbo.IDW_ACTIVITY.END_DATE, 112))
Run the script in SSMS, generate the execution plan, and create the indicies it suggests.