TSQL Convert String to Year only - sql-server

I have the following table:
SELECT * FROM [dbo].[Dimension_Game_Developer]
Table Schema:
Sample Data of select statement output:
I am trying to convert the string date as Year only date using the following:
update [dbo].[Dimension_Game_Developer]
SET [Year_of_Release] = CAST([Year_of_Release] as DATE)
How would I make that change? Perhaps convert is better the CAST for this?

You need to cast Year_of_Release as int as shown below.
update [dbo].[Dimension_Game_Developer]
SET [Year_of_Release] = CAST(Convert(Varchar(4), [Year_of_Release]) as int)
You can also convert it to float.
update [dbo].[Dimension_Game_Developer] SET [Year_of_Release] =
CAST([Year_of_Release] as float)
To solve the issue permanently you should updated the datatype of column Year_of_Release to int and insert the value in the integer further.
To change the column datatype:
ALTER TABLE [dbo].[Dimension_Game_Developer] ALTER COLUMN Year_of_Release int;

to format values ​​without the need for cast and substring
use the function Call Format o try_cast
example:
DECLARE #d DATETIME = '10/01/2011';
declare #tab table (StartDate date, year varchar(6),val1 int,val2 int)
insert into #tab(StartDate,year,val1,val2) values('2014-02-15','2015.0',0,0)
insert into #tab(StartDate,year,val1,val2) values('2015-02-15','2016.0',0,0)
insert into #tab(StartDate,year,val1,val2) values('2016-02-15','2017.0',0,0)
insert into #tab(StartDate,year,val1,val2) values('2017-02-15','2018.0',0,0)
update #tab SET [val1] = FORMAT ( StartDate, 'yyyy'),[val2] =try_cast(year as decimal(18,0))
select * from #tab
these two functions can be found in the sql server documentation

try DatePart(year,CAST([Year_of_Release] as DATE)) Year

Related

How to convert varchar into date datatype in inline functions sql

create table session12
(
id int,
name varchar(20),
Dateofbirth varchar(20)
);
insert into session12
values (1, 'prashanth', '29/06/1995'),
(2, 'rayala', '27/06/1997'),
(3, 'rayala1213', '7/9/2000');
create function inline_Getsession()
returns table
as
return
select
id, name,
cast(Dateofbirth as date) as DOB
from session12;
select *
from inline_Getsession();
Output:
Conversion failed when converting date and/or time from character string.
try this:
create table session12 (id int,name varchar(20),Dateofbirth varchar(20));`
insert into session12 values(1,'prashanth','29/06/1995');
insert into session12 values(2,'rayala','27/06/1997');
insert into session12 values(3,'rayala1213','7/9/2000');
create function inline_Getsession()
Returns Table
as
Return
select id,name,CONVERT(DATE,Dateofbirth,103) as DOB from session12;
select * from inline_Getsession();
You need to provide a date format of 103 when converting dd/mm/yyyy to date
You'll likely need to use CONVERT and a style code:
CONVERT(date,DateOfBirth,103)
103 style means the UK style (dd/MM/yyyy). You can find a full list of the styles in the CAST and CONVERT (Transact-SQL) documentation.
You could also set the DateFormat to DMY
If 2012+, I would suggest using try_convert(date,...) to avoid throwing an error for any bogus strings.
Example
Declare #session12 table (id int,name varchar(20),Dateofbirth varchar(20));
insert into #session12 values(1,'prashanth','29/06/1995');
insert into #session12 values(2,'rayala','27/06/1997');
insert into #session12 values(3,'rayala1213','7/9/2000');
Set DateFormat DMY
Select *
,AsADate = convert(date,DateOfBirth)
From #session12
Returns
id name Dateofbirth AsADate
1 prashanth 29/06/1995 1995-06-29
2 rayala 27/06/1997 1997-06-27
3 rayala1213 7/9/2000 2000-09-07

How to change datetime format of varchar datatype column

How to change datetime format of varchar datatype column in SQL Server.
Datatype of column [Value] is varchar. I cannot change datatype into datetime because this column contains numeric values also. This table is being updated by query. I need the format yyyy-mm-dd hh:mm:ss(24h). How?
You can use Try_Convert() in concert with IsNull()
To be clear. The result is still a string
Example
Declare #YourTable table (Value varchar(50))
Insert Into #YourTable values
('268142')
,('Jan 1 1900 12:04PM')
Select *
,NewVal = IsNull(format(try_convert(datetime,Value),'yyyy-MM-dd HH:mm:ss'),Value)
From #YourTable
Returns
Value NewVal
268142 268142
Jan 1 1900 12:04PM 1900-01-01 12:04:00
EDIT
Format() is not known to be a performer, and should be used sparingly. Another approach may be
NewVal = IsNull(try_convert(varchar(50),try_convert(datetime,Value),120),Value)
You can use this case-convert statement:
declare #date varchar(max)
set #date='Jan 1 1999 12:00AM'
Select case when right(#date,2)='AM' then convert(datetime,SUBSTRING(#date,1,len(#date)-2)+':00',121)
else dateadd(hour,12,convert(datetime,SUBSTRING(#date,1,len(#date)-2)+':00',121)) end

How to add a number to a year TSQL

I want to add a number to my date
For example I have column F9 which contains a date 2015.10.17 and I have a column F49 that has a number in it 10.
The end result should be 2025.10.17 so the number should only be added to the year and that’s it.
All three columns are of typ varchar
I have tried to do it as simple as possible but that does not work
UPDATE A.dbo.B
SET F29 = F9 + F49
If column type Data/datetime
UPDATE A.dbo.B SET F29 = DATEADD(year,F49,F9)
or this
F29 = CAST(CAST(SUBSTRING(F9,1,4) as INT) + F49 as VARCHAR(4)) + SUBSTRING(F9,5,LEN(F9))
Use DATEADD like below
UPDATE A.dbo.B
SET F29 = dateadd(year,F49,F9)
Test the functionality using below script:
DECLARE #Table TABLE (F9 VARCHAR(20), F49 VARCHAR(10))
INSERT INTO #Table VALUES ('2015.10.17', '10')
SELECT DATEADD(YEAR, CAST(t.F49 AS INT), CAST(t.F9 AS DATETIME))
FROM #Table AS t
And finally use following script to update:
UPDATE A.dbo.B
SET F29 = DATEADD(YEAR, CAST(t.F49 AS INT), CAST(t.F9 AS DATETIME))
Use roughly the exact same logic discussed in your previous question. You convert the F9 column as before, apply the dateadd function to it to add F49 as years, and then convert the result back to char(10) using the appropriate format. OR you could just fix your schema and never have to deal with these self-created problems.

Convert VARCHAR in format YYMMDD to YYYYMMDD and ignore invalid date formats

I have a table with a VARCHAR field called ArrivalDate in format yymmdd (such as 170202).
I am writing a query which converts it to yyyymmdd so it should become 20170202.
However my problem is that I need to cater for the case when inappropriate data is entered into the field, and my query needs to exclude that data. I am achieving this exclusion by using the ISDATE function of TSQL. I also need to select the least recent entry (I'm using order by asc for this).
I am using a variety of converts to write this query, below is my implementation with a sample table and data.
Declare #tmp TABLE (theDates VARCHAR(MAX))
INSERT INTO #tmp VALUES('170202')
SELECT TOP 1 t.theDates
WHEN (ISDATE(t.theDates) = 1) THEN CONVERT( VARCHAR(max),CONVERT(datetime t.theDates), 112)
FROM #tmp t
WHERE (ISDATE(t.theDates) = 1)
ORDER BY CAST(t.theDates as DATE)
However I do not like my approach and it occasionally fails conversion and throws an error with values such as 02/02/02 which breaks the query. Can someone please show me a better way of writing this functionality.
Much appreciated!
You can use TRY_CONVERT and CONVERT to get the correct format and convert the value. Then check that the string is exactly 6 character to prevent other formats from being returned.
SELECT
convert(char(10),convert(date, theDates, 12),112)
FROM
(values('02/02/02'),('170202')) x(theDates)
WHERE
try_convert(date, theDates, 12) is not null
and len(theDates) = 6
You can use cast(#date as datetime)
declare #date varchar(max);
set #date='170202';
select
CASE WHEN (ISDATE(cast(#date as datetime)) = 1)
THEN CONVERT(VARCHAR(max), CONVERT(datetime, cast(#date as datetime)), 112) end
from table
set #date='02/02/02';
select
CASE WHEN (ISDATE(cast(#date as datetime)) = 1)
THEN CONVERT(VARCHAR(max), CONVERT(datetime, cast(#date as datetime)), 112) end
from table
please use create function for check dateformat is Valid or not and use this fun in your query inside cash clouse.
ALTER FUNCTION dbo.f_CheckDate
(#InDate nvarchar(25))
RETURNS DATE
AS
BEGIN
declare #Return DATETIME
select #return = CASE WHEN ISDATE(#InDate) = 1
THEN #InDate
ELSE NULL
END
return #return
END
You could use TRY_CAST or TRY_CONVERT if value cannot be cast it will return NULL.
SELECT
TRY_CAST('20170228' AS DATETIME),
TRY_CAST('170228' AS DATETIME),
TRY_CONVERT(DATETIME, '20170228'),
TRY_CONVERT(DATETIME, '170228')
This works for SQL Server 2012 and newer.

Converting nvarchar to numeric

I have variable called #prmclientcode which is nvarchar. The input to this variable can be a single client code or multiple client codes separated by comma. For e.g.
#prmclientcode='1'
or
#prmclientcode='1,2,3'.
I am comparing this variable to a client code column in of the tables. The data type of this column is numeric(6,0). I tried converting the variable data type like below
SNCA_CLIENT_CODE IN ('''+convert(numeric(6,0),#prmclientcode+''')) (The query is inside a dynamic sql).
But when I try executing this I get the error
Arithmetic overflow error converting nvarchar to data type numeric.
Can anyone please help me here!
Thanks!
You need to convert the numeric(6,0) column to nvarchar data type. You can use below scrip to convert it to nvarchar, before processing:
SNCA_CLIENT_CODE IN ('''+convert(cast( numeric(6,0) as nvarchar(max) ),#prmclientcode+'''))
Please try with the below code snippet.
DECLARE #ProductTotals TABLE
(
ProductID int
)
INSERT INTO #ProductTotals VALUES(1)
INSERT INTO #ProductTotals VALUES(11)
INSERT INTO #ProductTotals VALUES(3)
DECLARE #prmclientcode VARCHAR(MAX)='1'
SELECT * FROM #ProductTotals
SELECT * FROM #ProductTotals WHERE CHARINDEX(',' + CAST(ProductID AS VARCHAR(MAX)) + ',' , ',' + ISNULL(#prmclientcode,ProductID) + ',') > 0
Let me know if any concern.
use following code in order to separate your variable:
DECLARE
#T VARCHAR(100) = '1,2,3,23,342',
#I int = 1
;WITH x(I, num) AS (
SELECT 1, CHARINDEX(',',#T,#I)
UNION ALL
SELECT num+1,CHARINDEX(',',#T,num+1)
FROM x
WHERE num+1<LEN(#T)
AND num<>0
)
SELECT SUBSTRING(#T,I,CASE WHEN num=0 THEN LEN(#T)+1 ELSE num END -I)
FROM x
Use can use either table function or dynamic sql query, both options will work.
Let me know if you need more help

Resources