Change date difference with CASE calculation - sql

I have a holding table for data, before adding to a final table in my database.
Within that table is a datediff calculation, which returns the number of days in a month.
However, this is baased on projects and what I need to do is look up the Project ID in another table, to see whether the TimeID (Year/Month) is equal to either the Start- or End-Date of the project.
When it matches either, it needs to change the number of days for that month to either Month-Start to Project-Finish (if it's the end month) or Project-Start to Month-End (if it's the start month).
I've tried to do this with the following script but I get the errors:
*** This bit is sorted, please see below ***
Msg 156, Level 15, State 1, Line 15
Incorrect syntax near the keyword 'FROM'.
Msg 102, Level 15, State 1, Line 23
Incorrect syntax near 'A'.
*** This bit is sorted, please see below ***
* EDIT *
Thanks to Anton, I've added the required END to my CASE statement, but I now get a different set of errors (probably down to my syntax):
Msg 207, Level 16, State 1, Line 23
Invalid column name 'TimeID'.
Msg 207, Level 16, State 1, Line 20
Invalid column name 'TimeID'.
Msg 207, Level 16, State 1, Line 26
Invalid column name 'ID'.
Msg 207, Level 16, State 1, Line 28
Invalid column name 'ID'.
Please help if you can.
The script is:
UPDATE FAC
SET FAC.[SignedData] =
CASE
WHEN FAC.[TIMEID] = A.[Start_TimeID] THEN
CASE
WHEN pd.[Start_Date] >= GETDATE() THEN datediff(day,pd.[Start_Date],pt.[Period_End])
WHEN pd.[Start_Date] < GETDATE() THEN datediff(day,GETDATE(),pt.[Period_End])
END
WHEN FAC.[TIMEID] = A.[End_TimeID] THEN
CASE
WHEN pd.[End_Date] >= GETDATE() THEN datediff(day,getdate(),pd.[End_Date])
WHEN pd.[End_Date] < GETDATE() THEN '0'
END
END
FROM Temp_Fac2Programme FAC
JOIN
(
SELECT
pd.[TimeID], pd.[Start_TimeID], pd.[End_TimeID], pt.[Period_Start], pt.[Period_End]
FROM ProjectDates pd
JOIN ProjectTimeID pt
on pd.[TimeID] = pt.[TimeID]
) A
ON A.[ID] = FAC.[Project]
Where A.[ID] = FAC.[Project]
GO
NB - SIGNEDDATA is the number of days in the month.
* Example Data *
Temp_Fac2Programme (FAC) contains:
ACCOUNT CATEGORY DATASRC PROFITCENTRE PROJECT RPTCURRENCY TIMEID SIGNEDDATA SOURCE
REMAIN_DAYS_FLAG ACTUAL DS_FLAGS B9059 AAA_7915_BBOY LC 20130100 34.0000000000 0
ProjectDates (pd) contains:
PROJECT_ID START_TIMEID END_TIMEID START_DATE END_DATE TOTAL_DAYS
PAG_5244_CASH 20110400 20120300 2011-04-01 2012-03-31 365
ProjectTimeID (pt) contains:
TIMEID PERIOD_START PERIOD_END DAYS_IN_PERIOD PCMONTHSTAT
20140600 2014-05-31 2014-06-27 27 F

As of the current (edited) version, it's basically what error messages say:
You use pd.[TimeID] in two places, but there is no TimeID column in ProjectDates (for now, I have no idea what you meant here).
Your subquery (aliased to A) has no ID column. The likely fix is adding pd.[Project_ID] as ID into the subquery's list of selected fields.

Related

Parsing txt file with substring

I inherited a SQL code from my previous co-worker. The script was working the last time I ran it but it returns an error when I tried it today. Surprisingly the code is working on my colleague's PC. I double-check the SQL server database and we are using the same collation, Latin1_General_CS_AS. I did many tests, changing windows system locale etc however none of them work, the error is this:
Msg 207, Level 16, State 1, Line 141
Invalid column name 'Value'.
Msg 207, Level 16, State 1, Line 141
Invalid column name 'Value'.
...
However, I couldn't get it! why it is working on one system and not on another! Does anybody has any idea or alternative solution for the substring part.
DROP TABLE IF EXISTS #VievingLive0
SELECT
ProdDay, -- date
HouseId, -- ID
CAST(SUBSTRING(RowText, 2, CHARINDEX('_', RowText, 2)-2) AS INT) AS ChannelId, -- Channel ID
CASE WHEN LEN(s.Value) = 14 THEN LEFT(s.Value, 2) ELSE STUFF(LEFT(s.Value, LEN(s.Value)-12), 3, 0, '_') END AS Individs, -- list of persons
(LEN(s.Value)-12)/2 AS CntIndiv, -- number of persons watching
DATEADD(SECOND, substring(s.Value,LEN(s.Value)-11,2)*3600+substring(s.Value,LEN(s.Value)-9,2)*60+substring(s.Value,LEN(s.Value)-7,2), CAST(ProdDay AS DATETIME)) AS ViewFrom, -- time from
DATEADD(SECOND, substring(s.Value,LEN(s.Value)-5 ,2)*3600+substring(s.Value,LEN(s.Value)-3,2)*60+substring(s.Value,LEN(s.Value)-1,2)+1, CAST(ProdDay AS DATETIME)) AS ViewTo -- time to
INTO #VievingLive0
FROM #All_TX4_files
CROSS APPLY STRING_SPLIT(SUBSTRING(RowText, PATINDEX('%_[A-Za-z][A-Za-z][A-Za-z0-9]%', SUBSTRING(RowText, 2, LEN(RowText)))+2, LEN(RowText)), '_') AS s -- extracting individual vieiwng statemenets from the row
WHERE LEFT(RowText, 1) = 'V' -- LIVE viewing rows
I am trying to parse this format txt:
H98500410_0
W1941.51
Pab_2467211514110343733611_W2898.81
V100_0_2_210_ab075700080859_ab081100081259_ab081700081959_ab082800083059_ab083400083559_ab110600110959_ab111300111459_ab113500115059_ab115300120259_ab120300120359_ab120400123059_ab123100123559_ab124800125359_ab173200173259_ab191200191359_ab191600191759

Could not find server 'STLEDGSQL01' in sysservers. Execute sp_addlinkedserver to add the server to sysservers?

The following SQL script is what I'm trying to execute using SQL Server Management Studio to get my end result and one of the stackoverflow member answered this script as per my needs, so I'm assuming the script is correct. But the issue is when I execute the script it gives me the following error.
Script
SELECT
ID,
RTRIM(trx_date), RTRIM(work_order), RTRIM(department),
RTRIM(work_center), RTRIM(operation_no), RTRIM(operator),
RTRIM(total_labor_hours), RTRIM(feet_produced),
RTRIM(item_no), RTRIM(lot_no), RTRIM(default_bin), RTRIM(posted)
FROM
NOR_LABOR
WHERE
ID > (SELECT MAX(SOURCE_ID)
FROM [STLEDGSQL01].[MES_DEV].[dbo].[ALL_LABOR_DETAILS]
WHERE work_center LIKE ('%NOR%'))
ORDER BY
ID
Error
Msg 7202, Level 11, State 2, Line 1
Could not find server 'STLEDGSQL01' in sysservers. Execute sp_addlinkedserver to add the server to sysservers.
I have tried to execute that statement in many different ways since my colleagues advised me adding the 'SERVER' and 'DATABASE' might be little extraneous but still keep getting errors as below
Keeping all the source and destination server/database/table name.
SELECT * FROM [Normac Data].[dbo].[NOR_LABOR] WHERE ID > (SELECT MAX(SOURCE_ID) FROM [STLEDGSQL01].[MES_DEV].[dbo].[ALL_LABOR_DETAILS] WHERE work_center LIKE '%NOR%') ORDER BY ID
Error : Msg 7202, Level 11, State 2, Line 1
Could not find server 'STLEDGSQL01' in sysservers. Execute sp_addlinkedserver to add the server to sysservers.
Removing the destination 'server' only and keeping everything else same.
SELECT * FROM [Normac Data].[dbo].[NOR_LABOR] WHERE ID > (SELECT MAX(SOURCE_ID) FROM [MES_DEV].[dbo].[ALL_LABOR_DETAILS] WHERE work_center LIKE '%NOR%') ORDER BY ID
Error : Msg 208, Level 16, State 1, Line 2
Invalid object name 'MES_DEV.dbo.ALL_LABOR_DETAILS'.
Removing the destination 'server' and 'database' only and keeping everything else same.
SELECT * FROM [Normac Data].[dbo].[NOR_LABOR] WHERE ID > (SELECT MAX(SOURCE_ID) FROM [dbo].[ALL_LABOR_DETAILS] WHERE work_center LIKE '%NOR%') ORDER BY ID
Error : Msg 208, Level 16, State 1, Line 3
Invalid object name 'dbo.ALL_LABOR_DETAILS'.
Removing the destination 'server' and 'database' and 'dbo' only and keeping everything else same.
SELECT * FROM [Normac Data].[dbo].[NOR_LABOR] WHERE ID > (SELECT MAX(SOURCE_ID) FROM ALL_LABOR_DETAILS WHERE work_center LIKE '%NOR%') ORDER BY ID
Error : Msg 208, Level 16, State 1, Line 4
Invalid object name 'ALL_LABOR_DETAILS'.
Removing the source server only and keeping everything else same.
SELECT * FROM [dbo].[NOR_LABOR] WHERE ID > (SELECT MAX(SOURCE_ID) FROM ALL_LABOR_DETAILS WHERE work_center LIKE '%NOR%') ORDER BY ID
Error : Msg 208, Level 16, State 1, Line 8
Invalid object name 'ALL_LABOR_DETAILS'.
Removing the source server and database only and keeping everything else same.
SELECT * FROM NOR_LABOR WHERE ID > (SELECT MAX(SOURCE_ID) FROM ALL_LABOR_DETAILS WHERE work_center LIKE '%NOR%') ORDER BY ID
Error : Msg 208, Level 16, State 1, Line 9
Invalid object name 'ALL_LABOR_DETAILS'.
I tried everything that I know but still not working, what else can I do to make this query work? Thank you all!

Msg 102, Level 15, State 1, Line 1 Incorrect syntax near 'Step 9: _RMP allocation current month'

I'm getting the following error
Msg 102, Level 15, State 1, Line 1 Incorrect syntax near 'Step 9: _RMP allocation current month'.
When i use the following insert and where clause:
INSERT INTO dbo.TrialRun [(Step 9: _RMP allocation current month)]
SELECT (RMP_prevMonth)
FROM dbo.TrialRun
WHERE Step7 > 200 and Step8>0
Did you really name your column Step 9: _RMP allocation current month?
(well, at least it's not Robert';DROP TABLE Students;--...)
The problem is that the columns list should be enclosed inside parenthesis:
INSERT INTO dbo.TrialRun ([(Step 9: _RMP allocation current month)])
SELECT RMP_prevMonth
FROM dbo.TrialRun
WHERE Step7 > 200
AND Step8 > 0
But I'm guessing the column name is simply Step9 (as suggested by other column names in your statement) so your statement should probably look like this:
INSERT INTO dbo.TrialRun (Step9)
SELECT RMP_prevMonth
FROM dbo.TrialRun
WHERE Step7 > 200
AND Step8 > 0

SQL Help - If Then Else

I need the help of someone who understands SQL better than I do...
I am trying to make a single SP call that uses the IF THEN ELSE but keep getting three "the multi-part identifier could not be bound" messages.
Pages can be sponsored by a Business or a Group.
In the advertEntityType field I have a "B" or a "G" for business or group.
In the advertEntityID field I have the businessID or groupID.
SELECT
Advertisements.advertEntityType
,Advertisements.advertEntityID
FROM Advertisements
WHERE Advertisements.advertPageName = #pageName
IF (Advertisements.advertEntityType = 'G')
SELECT
Group.groupID
,Group.groupName
,Group.groupPhone
,Group.groupWebsite
,Group.groupLogoName
FROM Group
WHERE Group.groupID = Advertisements.advertEntityID
ELSE
SELECT
Business.businessID
,Business.businessName
,Business.businessWorkPhone
,Business.businessWebsite
,Business.businessLogoName
FROM Business
WHERE Business.businessID = Advertisements.advertEntityID
When I try to execute I get these messages which I cannot seem to get my head around...
Msg 4104, Level 16, State 1, Procedure Sponsor_s01, Line 36
The multi-part identifier "Advertisements.advertEntityType" could not be bound.
Msg 4104, Level 16, State 1, Procedure Sponsor_s01, Line 46
The multi-part identifier "Advertisements.advertEntityID" could not be bound.
Msg 4104, Level 16, State 1, Procedure Sponsor_s01, Line 58
The multi-part identifier "Advertisements.advertEntityID" could not be bound.
Advertisements.advertEntityType is a table name and column name. You need to assign these values to local variables if you want to use them in if statements. If I understand correctly you want to evaluate based on the condition in the first select statement. In this case you should use such query:
DECLARE #entityType int --assuming the type of Advertisements.advertEntityType is int
DECLARE #advertEntityID int --assuming the type of Advertisements.advertEntityID is int
SELECT
#entityType = Advertisements.advertEntityType,
#advertEntityID = Advertisements.advertEntityID
FROM Advertisements
WHERE Advertisements.advertPageName = #pageName
IF (#entityType = 'G')
SELECT
Group.groupID
,Group.groupName
,Group.groupPhone
,Group.groupWebsite
,Group.groupLogoName
FROM Group
WHERE Group.groupID = #advertEntityID
ELSE
SELECT
Business.businessID
,Business.businessName
,Business.businessWorkPhone
,Business.businessWebsite
,Business.businessLogoName
FROM Business
WHERE Business.businessID = #advertEntityID

Dynamic UPDATE statement

I want to create a dynamic update query where I need to set a certain value in a column. But the column name needs to be SELECTed from another table.
I have already the following query:
UPDATE core.TableRes
SET (
SELECT Code FROM core.TableFields
INNER JOIN core.TableXTableFields ON TableXTableFields.FieldID = TableFields.FieldID
INNER JOIN core.TableResRefLinks ON TableResRefLinks.ExtraFieldID = TableXTableFields.ExtraFieldID
WHERE TableResRefLinks.TableResRefLinksID = RefLinks.TableResRefLinksID)
= (
SELECT Value FROM core.TableResRefLinks WHERE TableResRefLinksID = RefLinks.TableResRefLinksID)
FROM core.TableRes
INNER JOIN core.TableResRefLinks RefLinks ON RefLinks.ResourceID = TableRes.ResourceID
INNER JOIN core.TableXTableFields ON TableXTableFields.ExtraFieldID = RefLinks.ExtraFieldID
INNER JOIN core.TableFields ON TableFields.FieldID = TableXTableFields.FieldID
WHERE (EndDate IS NULL OR EndDate > GETDATE()) AND
(
SELECT Code FROM core.TableFields
INNER JOIN core.TableXTableFields ON TableXTableFields.FieldID = TableFields.FieldID
INNER JOIN core.TableResRefLinks ON TableResRefLinks.ExtraFieldID = TableXTableFields.ExtraFieldID
WHERE TableResRefLinks.TableResRefLinksID = RefLinks.TableResRefLinksID)
<>
(
SELECT Value FROM core.TableResRefLinks
WHERE TableResRefLinksID = RefLinks.TableResRefLinksID)
It gives me the following errors:
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '('.
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '='.
Msg 156, Level 15, State 1, Line 5
Incorrect syntax near the keyword 'FROM'.
Msg 102, Level 15, State 1, Line 14
Incorrect syntax near '<'.
Is there a way to solve this? If I change the complete UPDATE and SET statements and replace them with a SELECT *, I get results.
EDIT
Here are the datatypes
TableFields.Code => nvarchar(100)
TableResRefLinks.Value => sql_variant
And the datatypes of the columns that have as column name TableFields.Code are set as sql_variant
You can't solve this using plain SQL. You would need some kind of scripting to build your statement. For example postgresql has a scripting language called "pgpsql" which allows building dynamic SQL statements. But this clearly depends on the underlying RDBMS.
By the way: this works with SELECT as you are doing simple sub-select.