Parsing txt file with substring - sql

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

Related

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!

Convert date from AS/400 database file

I'm using MS SQL Server and am Trying to convert the date and time data into something useful for PowerBi and
can't get the time to work, Date is fine:
USE [CDCP_AEP]
GO
select *
from
(SELECT [H1PROD]
,convert(DATE,right('0'+str([H1DTTR],len([H1DTTR])),6),102) as 'AssyDate'
,[H1TMTR]
,right('000000'+str([H1TMTR],len([H1TMTR])),6) 'TempTime'
,[H1TYPE]
,[H1LOT]
,[H1SORD]
from [AEBPCSUSRF].[JHP1]
where [H1TYPE] = 'AF' and [H1LOT] <> '')a
left join
(select [P1PROD]
,[P1LOT]
from [AEBPCSUSRF].[PLA1])b
on a.[H1LOT] = b.[P1LOT]
GO
This is the result I get with the above code:
If I change the date (H1TMTR) line to
,convert(TIME,right('000000'+str([H1TMTR],len([H1TMTR])),6)) as 'AssyTime'
I get the following error:
"Msg 241, Level 16, State 1, Line 4
Conversion failed when converting date and/or time from character string."
Any tips? Thanks in advance!
You can convert by padding, substring'ing, and putting colons in between the parts like so:
DECLARE #H1TMTR VARCHAR(6)='155509'
SELECT CONVERT(TIME,
SUBSTRING(RIGHT('000000' + #H1TMTR,6),1,2) + ':'
+ SUBSTRING(RIGHT('000000' + #H1TMTR,6),3,2) + ':'
+ SUBSTRING(RIGHT('000000' + #H1TMTR,6),5,2)
) AS [Time]
Since you are doing this for PowerBI, I presume you will be doing this quite a bit. You should make a scalar function that performs this task on a column so it only needs written once.

Change date difference with CASE calculation

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.

inserting multiple values into a single cell using sql 2005

I have the typical table:
LSRNbr BatchNbr
111 1212
111 1414
And the query should return:
LSRNbr BatchNbr
111 1212, 1414
I was browsing for a solution to this and I found these two:
Solution 1:
;WITH C AS
(
SELECT LSRNbr, BatchNbr FROM tblDTS_LSRBatch
)
SELECT Distinct LSRNbr,
STUFF((SELECT ';' + BatchNbr FROM tblDTS_LSRBatch WHERE LSRNbr = c.LSRNbr FOR XML PATH('')),1,1,'')
FROM C
error:
Msg 170, Level 15, State 1, Line 1
Line 1: Incorrect syntax near ';'.
Msg 170, Level 15, State 1, Line 7
Line 7: Incorrect syntax near 'XML'.
Solution 2:
SELECT
[LSRNbr], REPLACE(RTRIM((SELECT [BatchNbr] + ' ' FROM tblDTS_LSRBatch WHERE (LSRNbr = Results.LSRNbr ) FOR XML PATH (''))),' ',', ') AS NameValues
FROM tblDTS_LSRBatch Results
GROUP BY LSRNbr
error:
Msg 170, Level 15, State 1, Line 2
Line 2: Incorrect syntax near 'XML'.
But none of them worked for me, see errors above please.
What could be the problem here?
I'm using Microsoft SQL Server 2005
These are syntax errors.
You'll learn more from figuring out the particular error yourself:
Take a look at the syntax tree
Take a look at some good examples of what you're trying to do
If you still have trouble, feel free to ask more questions

sql insert into values The multi-part identifier could not be bound

I am trying to run this command which shoulld append 80 rows.. but i get.
Msg 4104, Level 16, State 1, Line 1
The multi-part identifier "Frame.Guid" could not be bound.
INSERT INTO studentrecords(recordGuid, studentGuid, courseGuid, licenseGuid, repeatflag, frameGuid, coredata, framescore, timeinframe, locked, daterefreshed, dateinserted)
VALUES (NEWID(), '25d6e1d9-e5ce-42dd-bd6a-5956ec7cb047', '54dffd58-1af9-44cf-982e-ea0e8930878e', '00000000-1111-1111-0000-000000000000', 0, Frame.Guid, '<flags><flag1>1</flag1> <flag2>1</flag2> <flag3>1</flag3> <flag4>1</flag4> <flag5>1</flag5><flag6>1</flag6></flags><StudentAnswer> <CorrectionHistory></CorrectionHistory> </StudentAnswer>', 0, 55860, 1, GETDATE(), GETDATE())
Select Frame.Guid FROM Frame
WHERE (Frame.Course = '54dffd58-1af9-44cf-982e-ea0e8930878e') AND (Frame.Template <> '7d3a3b40-86e3-43f4-a4ca-039afdd0b7a3')
INSERT INTO studentrecords (
recordGuid, studentGuid, courseGuid, licenseGuid,
repeatflag, frameGuid, coredata,
framescore, timeinframe, locked,
daterefreshed, dateinserted
)
SELECT NEWID(),
'25d6e1d9-e5ce-42dd-bd6a-5956ec7cb047',
'54dffd58-1af9-44cf-982e-ea0e8930878e',
'00000000-1111-1111-0000-000000000000',
0, Frame.Guid, '1 1 1 1 11 ', 0, 55860, 1,
GETDATE(), GETDATE()
FROM Frame
WHERE Frame.Course = '54dffd58-1af9-44cf-982e-ea0e8930878e'
AND Frame.Template <> '7d3a3b40-86e3-43f4-a4ca-039afdd0b7a3';
I can't see how you want the "insert" and "select" queries here to be related -- they're both syntactically complete but not linked in any way. You're expecting "Frame.Guid" in the first query to come from the second query, somehow, but I can't quite get how. In any case, that's all that the error message is saying; it can't tell what you mean by Frame.Guid, exactly.
You're referencing Frame.Guid in the insert statement, but there isn't one defined. I suspect you want to select that value into a variable, then use the variable in the insert statement.
DECLARE #frameGUID GUID
SET #frameGUID = (Select Frame.Guid FROM Frame
WHERE (Frame.Course = '54dffd58-1af9-44cf-982e-ea0e8930878e')
AND (Frame.Template <> '7d3a3b40-86e3-43f4-a4ca-039afdd0b7a3'))
INSERT INTO studentrecords(recordGuid, studentGuid, courseGuid, licenseGuid, repeatflag, frameGuid, coredata, framescore, timeinframe, locked, daterefreshed, dateinserted)
VALUES (
NEWID(),
'25d6e1d9-e5ce-42dd-bd6a-5956ec7cb047',
'54dffd58-1af9-44cf-982e-ea0e8930878e',
'00000000-1111-1111-0000-000000000000',
0,
#frameGUID,
'<flags><flag1>1</flag1> <flag2>1</flag2> <flag3>1</flag3> <flag4>1</flag4> <flag5>1</flag5><flag6>1</flag6></flags><StudentAnswer> <CorrectionHistory></CorrectionHistory> </StudentAnswer>',
0,
55860,
1,
GETDATE(),
GETDATE())
You have two statements there. The INSERT statement has no way of knowing that you want the field Frame.Guid out of the SELECT statement.
You need to refactor it into one statement. You can do that by putting all the constants into the SELECT statement (between SELECT and FROM) and deleting the VALUES clause. Then it will be one statement.