CAST number as varchar, then update into another table as date - sql

I'll as brief as possible, but start by saying I'm a network guy, not a DBA.
SQL Server Enterprise 11.0.5343
Scenario - Need to get three columns (each with a part of a date) together, and then update another table with the full date.
Source table: UT210AP
Columns:
UTONMM (Utility On Month - 2 digit)
UTONDD (Utility On Day - 2 digit)
UTONYY (Utility On Year - 2 digit)
UTONCV (Utility On Century - 0 = 19xx, 1 = 20xx)
I can select the data into a "date" with this code (the source data is on an IBM AS/400 linked server)
CAST(UTONMM as varchar) + '/' +
CAST(UTONDD as varchar) + '/' +
CASE WHEN UTONCV = '1'
THEN
RIGHT('20' + CONVERT(varchar(4), RIGHT('00' + CONVERT(varchar(4),UTONYY),2)),4)
ELSE
RIGHT('19' + CONVERT(varchar(4), UTONYY),4)
END AS UTON
And I get these results in the column I named "UTON":
4/6/1994
7/1/1988
11/14/1990
6/6/2014
QUESTION:
I have a nightly import job that runs, and I need to get the "date" (like 4/6/1994) into a field called TIME_CONNECT as part of this update statement from the job:
Update [responder].[Temp_RX_CUSTOMERS]
set CustomerID = lf.UTCSID
from [responder].[Temp_RX_CUSTOMERS] LEFT Outer Join
[HTEDTA].[THOR].[HTEDTA].UT210AP lf ON [responder].[Temp_RX_CUSTOMERS].LocationID = lf.UTLCID
where lf.UTOFMM = 0
The "UTOFMM" in the code above is "Utility Off Month", I don't even care about checking for it's value, I just want to get the "UTON" date from the top select statement into the "TIME_CONNECT" field in the "Temp_RX_CUSTOMERS" field.

Is this what you want? This copies the value into the field, assuming time_connect is a string.
Update [responder].[Temp_RX_CUSTOMERS]
set CustomerID = lf.UTCSID,
time_connect = (CAST(UTONMM as varchar) + '/' +
CAST(UTONDD as varchar) + '/' +
(CASE WHEN UTONCV = '1'
THEN RIGHT('20' + CONVERT(varchar(4), RIGHT('00' + CONVERT(varchar(4),UTONYY),2)),4)
ELSE RIGHT('19' + CONVERT(varchar(4), UTONYY),4)
END)
)
from [responder].[Temp_RX_CUSTOMERS] LEFT Outer Join
[HTEDTA].[THOR].[HTEDTA].UT210AP lf
ON [responder].[Temp_RX_CUSTOMERS].LocationID = lf.UTLCID
where lf.UTOFMM = 0;
If time_connect is a date/datetime data type, you can use datefromparts() (available in SQL Server 2012+):
Update [responder].[Temp_RX_CUSTOMERS]
set CustomerID = lf.UTCSID,
time_connect = DATEFROMPARTS(1800 + UTONCV * 100 + UNONYY,
UTONMM, UTONDD)
from [responder].[Temp_RX_CUSTOMERS] LEFT Outer Join
[HTEDTA].[THOR].[HTEDTA].UT210AP lf
ON [responder].[Temp_RX_CUSTOMERS].LocationID = lf.UTLCID
where lf.UTOFMM = 0;

Related

Updating database column with string built based on value of another column

I have a table with a column called Days. The Days column stores a comma delimited string representing days of the week. For example the value 1,2 would represent Sunday, Monday. Instead of storing this information as a comma delimited string, I want to convert it to JSON and store it in a column called Frequency in the same table. For example, a record with the Days value of 1,2 should be updated to store the following in it's Frequency column:
'{"weekly":"interval":1,"Sunday":true,"Monday":true,"Tuesday":false,"Wednesday":false,"Thursday":false,"Friday":false,"Saturday":false}}'
I found a way to do this using a case statement assuming that there is only one digit in the Days column like so:
UPDATE SCH_ITM
SET
FREQUENCY =
CASE
WHEN SCH_ITM.DAYS = 1 THEN '{"weekly":{"interval":1,"Sunday":true,"Monday":false,"Tuesday":false,"Wednesday":false,"Thursday":false,"Friday":false,"Saturday":false}}'
WHEN SCH_ITM.DAYS = 2 THEN '{"weekly":{"interval":1,"Sunday":false,"Monday":true,"Tuesday":false,"Wednesday":false,"Thursday":false,"Friday":false,"Saturday":false}}'
WHEN SCH_ITM.DAYS = 3 THEN '{"weekly":{"interval":1,"Sunday":false,"Monday":false,"Tuesday":true,"Wednesday":false,"Thursday":false,"Friday":false,"Saturday":false}}'
WHEN SCH_ITM.DAYS = 4 THEN '{"weekly":{"interval":1,"Sunday":false,"Monday":false,"Tuesday":false,"Wednesday":true,"Thursday":false,"Friday":false,"Saturday":false}}'
WHEN SCH_ITM.DAYS = 5 THEN '{"weekly":{"interval":1,"Sunday":false,"Monday":false,"Tuesday":false,"Wednesday":false,"Thursday":true,"Friday":false,"Saturday":false}}'
WHEN SCH_ITM.DAYS = 6 THEN '{"weekly":{"interval":1,"Sunday":false,"Monday":false,"Tuesday":false,"Wednesday":false,"Thursday":false,"Friday":true,"Saturday":false}}'
WHEN SCH_ITM.DAYS = 7 THEN '{"weekly":{"interval":1,"Sunday":false,"Monday":false,"Tuesday":false,"Wednesday":false,"Thursday":false,"Friday":false,"Saturday":true}}'
END
WHERE SCH_TYPE = 'W';
However I cannot seem to figure out an effecient way to handle converting a value such as 1,5 into the correct JSON representation. Obviously I could write out every possible permutation, but surely is a better way?
Okay this will give you what you have asked for
create table test (days varchar(20), frequency varchar(500))
insert into test(days) values('1'),('2'),('3'),('4'),('5'),('6'),('7'),('1,5')
update test set frequency = '{"weekly":{"interval":1,'
+ '"Sunday": ' + case when days like '%1%' then 'true' else 'false' end + ','
+ '"Monday": ' + case when days like '%2%' then 'true' else 'false' end + ','
+ '"Tuesday": ' + case when days like '%3%' then 'true' else 'false' end + ','
+ '"Wednesday": ' + case when days like '%4%' then 'true' else 'false' end + ','
+ '"Thursday": ' + case when days like '%5%' then 'true' else 'false' end + ','
+ '"Friday": ' + case when days like '%6%' then 'true' else 'false' end + ','
+ '"Saturday": ' + case when days like '%7%' then 'true' else 'false' end + '}}'
select * from test
Though of course e.g. Days = '1234' will produce the same as '1,2,3,4' - as will 'Bl4arg3le12' for that matter. If Days is a string, you can put '8' which is meaningless?
Really it sounds like you need an extra table or two:
If "MyTable" is the table with the Days column, add a Days table with the days of the week, then a MyTableDays table to link MyTable entries to days - for the 1,5 example, there would be two rows in MyTableDays
With the help of a parse function and an cross apply
;with cteDays As (Select ID,Name From (Values(1,'Sunday'),(2,'Monday'),(3,'Tuesday'),(4,'Wednesday'),(5,'Thursday'),(6,'Friday'),(7,'Saturday')) D(ID,Name))
Update YourTable Set Frequency = '{"weekly":"interval":1,'+String+'}}'
From YourTable A
Cross Apply (
Select String = Stuff((Select ','+String
From (
Select String='"'+Name+'":'+case when RetVal is null then 'false' else 'true' end
From [dbo].[udf-Str-Parse](A.Days,',') A
Right Join cteDays B on RetVal=ID) N
For XML Path ('')),1,1,'')
) B
Select * from YourTable
Updated Table
Days Frequency
1,2 {"weekly":"interval":1,"Sunday":true,"Monday":true,"Tuesday":false,"Wednesday":false,"Thursday":false,"Friday":false,"Saturday":false}}
1,2,3 {"weekly":"interval":1,"Sunday":true,"Monday":true,"Tuesday":true,"Wednesday":false,"Thursday":false,"Friday":false,"Saturday":false}}
The UDF if needed
CREATE FUNCTION [dbo].[udf-Str-Parse] (#String varchar(max),#Delimiter varchar(10))
Returns Table
As
Return (
Select RetSeq = Row_Number() over (Order By (Select null))
,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
From (Select x = Cast('<x>'+ Replace(#String,#Delimiter,'</x><x>')+'</x>' as xml).query('.')) as A
Cross Apply x.nodes('x') AS B(i)
);
--Select * from [dbo].[udf-Str-Parse]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse]('John Cappelletti was here',' ')

Putting SQL record values in a single row

SQL isn't my expertise but, how do I write a SQL query that takes values from two different records and put them in one row? For example, I did a query on this EmployeeId, and I need the output values specifically from the Vacation_Type column for Adjust on 2016-07-01 (if it exists) and the Forward value from date 2016-08-01 (exists for every employee) ? Desired output would be:
26, SL, 547.58, -37.42
Not every employee would have an Adjust record, they have an Adjust when they are over the sick leave cap... and not everyone is over the cap. Thanks!
select
EV.EmployeeID,
EV.Vacation_Kind,
stuff( ( select ', ' + convert(varchar(30), EV1.Value) from EmployeeVacations EV1
where EV1.EmployeeID = EV.EmployeeID and EV1.Vacation_Kind = EV.Vacation_Kind
and EV1.VacationType in ('Adjust','Forward') and EV1.CreationDate IN (EV.CreationDate, dateadd(month, datediff(month, 0, dateadd(month, 1, EV.CreationDate)), 0))
for xml path('')
), 1, 1, '')
from
EmployeeVacations EV
where
EV.EmployeeID = 26 and EV.Vacation_Kind = 'SL'and VacationType = 'Adjust'
group by
EV.EmployeeID, EV.Vacation_Kind, EV.CreationDate
Since the 'Adjust' record isn't guaranteed to be there, you can use a LEFT OUTER JOIN. The following queries all employees, but you can uncomment the two lines if you really only want employee 26...
SELECT
CAST(fwd.EmployeeId AS varchar) + ', ' +
fwd.Vacation_Kind + ', ' +
CAST(fwd.[Value] as varchar) +
CASE WHEN adj.Value IS NULL THEN '' ELSE ', ' + CAST(adj.Value AS varchar) END
FROM
#employeeVacations fwd
LEFT OUTER JOIN #employeeVacations adj ON
adj.EmployeeId = fwd.EmployeeId)
AND
adj.Vacation_Kind = 'SL')
AND
adj.Vacation_Type = 'Adjust'
AND
adj.CreationDate = '2016-07-01'
WHERE
--fwd.EmployeeId = 26
--AND
fwd.Vacation_Kind = 'SL'
AND
fwd.Vacation_Type = 'Forward'
AND
fwd.CreationDate = '2016-08-01'

Conversion failed when converting the nvarchar value '29449,29446,29450,29534' to data type int

I am create a stored procedure in SQL and I get the following error when I execute the query:
Conversion failed when converting the nvarchar value '11021,78542,12456,24521' to data type int.
Any idea why?
SELECT
A.Art_ID, A.Title
FROM
Art A
INNER JOIN
Iss I ON A.Iss_ID = I.Iss_ID
INNER JOIN
Sections S ON A.Section_ID = S.Section_ID
INNER JOIN
iPadSec IPS ON A.Sec_ID = IPS.Sec_ID
WHERE
A.Art_ID IN (SELECT CAST(Art_IDs AS int) /***error happens here***/
FROM Book_Art b
WHERE Sub_ID = 68)
AND I.Iss > dateadd(month, -13, getdate())
AND A.Active = 1
AND IPS.Active = 1
AND A.PDate <= getdate()
ORDER BY
PDate DESC, Art_ID DESC;
You cannot do what you want using in. First, it is a really bad idea to store ids in lists in strings. You should be using a junction table.
That said, sometimes this is necessary. You can rewrite this line of code as:
EXISTS (SELECT 1 /***error happens here***/
FROM Book_Art b
WHERE Sub_ID = 68 AND
',' + Art_IDs + ',' LIKE '%,' + cast(A.Art_ID as varchar(255)) + ',%'
)
However, the performance would generally be on the lousy side and there is little prospect of speeding this up without fixing the data structure. Use a junction table instead of a string to store lists.
Adding this line works for me.
declare #ids varchar(1000)
select #ids = art_ids from book_art where sub_id = #Sub_ID
EXECUTE ( 'SELECT A.Art_ID, A.Title'
+ ' FROM Art A'
+ ' INNER JOIN Iss I ON A.Iss_ID = I.Iss_ID'
+ ' INNER JOIN Sections S ON A.Section_ID = S.Section_ID'
+ ' INNER JOIN iPadSec IPS ON A.Sec_ID = IPS.Sec_ID'
+ ' WHERE A.Art_ID IN (' + #ids + ')'
+ ' AND I.Iss > dateadd(month, -13, getdate())'
+ ' AND A.Active = 1'
+ ' AND IPS.Active = 1'
+ ' AND A.PDate <= getdate()'
+ ' ORDER BY PDate DESC,'
+ ' Art_ID DESC;'
)
END
Thank you all for your help :)

Update column with concatenated date (SQL Server)

I'm trying to update a column with the concatenated and converted results of two other columns in order to create a column with a date field. The SELECT statement returns the values I want to Update with, but I'm missing something (probably simple) on the update. It won't execute because
"the subquery returns more than one value".
However, I don't want to update with the same value for each row, but rather the concatenated result for each row.
What am I missing?
UPDATE myTable
SET myDate =
(
SELECT
CONVERT (Date,(CONVERT (NVarchar, CreatedYear) + '-' + CONVERT (NVarchar, CreatedMonth) + '-' + '01') ,0)
FROM myTable
)
I believe you have an extra SELECT that is not required. Please try:
UPDATE myTable
SET myDate =
CONVERT (Date,(CONVERT (NVarchar, CreatedYear) + '-' + CONVERT (NVarchar, CreatedMonth) + '-' + '01') ,0)
FROM myTable
This is a bit more readable in my opinion:
UPDATE dbo.tblControlMaster SET AuditAddDate = CAST(CreatedYear AS NVARCHAR(4)) + '-' + CAST(CreatedMonth AS NVARCHAR(2)) + '-' + '01'

how to parse for more than 4 positions

I have a funny case where a piece of data needed, is actually embedded in a column of data looking something like this:
note that is a shop with strong legacy mess still in place.
adlu201008270919_3.zip the date is what i need and is embedded.
I have code to do this here:
AND CAST(SUBSTRING(M.MDS_FILE,5,4) + '-' + SUBSTRING(M.MDS_FILE,9,2) + '-' + SUBSTRING(M.MDS_FILE,11,2) as datetime)
But now I find out that where you have here 'adlu' that is 4 pos. It can be 3 or 2 or 1.
So I have to code for that I have come up with this: but it's not compiling:
AND CASE WHEN WHEN CAST(SUBSTRING(M.MDS_FILE,5,4) + '-' + SUBSTRING(M.MDS_FILE,9,2) + '-' + SUBSTRING(M.MDS_FILE,11,2) as datetime)
ELSE WHEN OEN.LENGTH(S.FACILITY_KEY) = 3 THEN CAST(SUBSTRING(M.MDS_FILE,4,4) + '-' + SUBSTRING(M.MDS_FILE,8,2) + '-' + SUBSTRING(M.MDS_FILE,10,2) as datetime)
ELSE WHEN OEN.LENGTH(S.FACILITY_KEY) = 2 THEN CAST(SUBSTRING(M.MDS_FILE,3,4) + '-' + SUBSTRING(M.MDS_FILE,7,2) + '-' + SUBSTRING(M.MDS_FILE,9,2) as datetime)
ELSE CAST(SUBSTRING(M.MDS_FILE,2,4) + '-' + SUBSTRING(M.MDS_FILE,6,2) + '-' + SUBSTRING(M.MDS_FILE,8,2) as datetime) END
CASE requires an evaluation. Your first statement just says WHEN(a bunch of conversions) but there's never an evaluation (=, <, > etc).
I'm assuming you want that to be AND CASE WHEN OEN.LENGTH(s.FACILITY_KEY) = 4 THEN ...
Instead of a CASE statement based of S.FACILITY_KEY, I would use PATINDEX to dynamically find the start position of the date string that you're looking for:
DECLARE
#TestValue1 VARCHAR(50),
#TestValue2 VARCHAR(50),
#TestValue3 VARCHAR(50),
#TestValue4 VARCHAR(50)
SET #TestValue1 = 'adlu201008270919_3.zip'
SET #TestValue2 = 'adl201008270919_3.zip'
SET #TestValue3 = 'ad201008270919_3.zip'
SET #TestValue4 = 'a201008270919_3.zip'
SELECT CAST(SUBSTRING(#TestValue1, PATINDEX('%[1-2][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%', #TestValue1), 8) AS DATETIME)
SELECT CAST(SUBSTRING(#TestValue2, PATINDEX('%[1-2][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%', #TestValue2), 8) AS DATETIME)
SELECT CAST(SUBSTRING(#TestValue3, PATINDEX('%[1-2][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%', #TestValue3), 8) AS DATETIME)
SELECT CAST(SUBSTRING(#TestValue4, PATINDEX('%[1-2][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%', #TestValue4), 8) AS DATETIME)