Converting datetime to short date from a declared table in sql - sql

This is my first question on StackOverflow so I apologize for this most likely being formatted incorrectly. I am very new to sql language and am having trouble with the following query:
I have a declared table with one row selecting for a datetime (OccurrenceGroupID) and would like to have that date show up with short date formatting in the query results.
--Select for Occurrence Group
Declare #A3 table (OccurrenceGroupID datetime)
insert into #A3
select OccurrenceGroup as OccurrenceGroup,
Convert(VARCHAR(10),GETDATE(), 101) as [MM/DD/YYYY]
from tblOccurrenceGroup
where occurrencegroupid = #occurrencegroupid
I get the error message "Column name or number of supplied values does not match table definition."
Any help would be much appreciated.
Thanks.

Your error is because you are selecting two columns and trying to insert the result set into a table with only one column.
Regardless of this you are converting a datetime to a varchar presumably for presentation reasons and then wanting to insert it into a column of type datetime which doesn't make much sense. Always leave the formatting of dates to the client application.

you have declared it as datetime
Declare #A3 table (OccurrenceGroupID datetime)
so it expects a date and a time you the go on to say
Convert(VARCHAR(10),GETDATE(), 101) as [MM/DD/YYYY]
you then say convert the varchar as MM/DD/YYYY therefor it is contradictory to your first statement

Related

How to find the wrong dates after an 'out-of-range value' error in SQL Server?

I want to convert a column in the format mm/dd/yyyy to datetime, but when I do I get the following error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
I found in other posts that this means that some dates don't make sense, such as 10/35/2021. I tried to find the wrong dates by slicing the varchars to get the dates with SUBSTRING(date, 3, 2) but it turns out some dates are in the form m/d/yyyy, so when I slice I get something like 1/.
I have no idea how to find the wrong dates, and how to (even though there are wrong dates) convert everything to datetime.
Thanks!
If some of your data is in MM/dd/YYYY and some M/d/yyyy this really makes for a bit of a mess. I would likely do something like this:
--Add a new varchar column (yes varchar) to save a copy of your bad data
ALTER TABLE dbo.YourData ADD BadDate varchar(10);
GO
--Change the data you have to the ISO format yyyyMMdd and store the bad data in the BadDate column
UPDATE dbo.YourData
SET DateColumn = CONVERT(varchar(8),TRY_CONVERT(date,DateColumn,101),112),
BadDate = CASE WHEN TRY_CONVERT(date,DateColumn,101) IS NULL THEN DateColumn END
WHERE DateColumn IS NOT NULL;
GO
--Change data type of your data column
ALTER TABLE dbo.YourData ALTER COLUMN DateColumn date NULL;
GO
--You can view your bad data with:
SELECT BadData
FROM dbo.YourData
WHERE BadData IS NOT NULL;
If you just want to locate rows with values that are obviously bad dates - disregarding any ambiguities - just use try_convert and check for NULLs
eg
with dates as (
select * from (values('01/02/2021'),('02/01/2021'),('33/02/2021'),('01/13/2021'))v(d)
)
select *
from dates
where Try_Convert(date, d) is null

SQL - Conversion failed when converting date and/or time from character string

I have 3 tables in the database that I'm working on. Out of 3, two of the tables have columns that include dates. When I checked the information schema of the columns I found that dates have the wrong data type. If you see the picture below, the highlighted columns should be stored as DATE data type.
So, I used the following query to change their data type from varchar to DATE:
ALTER TABLE [dbo].[Customer]
ALTER COLUMN DOB DATE;
ALTER TABLE [dbo].[Transactions]
ALTER COLUMN tran_date DATE;
The error that I get is:
Conversion failed when converting date and/or time from character string.
Please let me know how I can fix this error. Thanks!
What you can do is update the value using try_convert() first and then alter the column name. Note: This will set any invalid values to NULL.
update customer
set dob = try_convert(date, dob);
alter table customer alter column dbo date;
If you want to see the bad values, then before you change the table, run:
select c.*
from customer c
where try_convert(date, dob) is null and dob is not null;
You may have other ideas on how to fix the values.
You can't change from varchar to date or time or datetime by altering the column. Why? Because SQL Server does not know if the field contains '1/1/2020' or 'My dog is cute'. You will have to rebuild the table with the proper data types and then CAST() or CONVERT() the values to a true date time.
Underneath the hood, this makes more sense. A char/varchar uses one byte per character. nchar/nvarchar uses 2 bytes per character. A datetime is a number, not a character. This means you need a routine that changes this into the correct number. If you want to get deeper, the number is the number of ticks (nanoseconds) since midnight on January 1, 0001 in the Gregorian Calendar. More info.

Why can't I insert yyyymmdd (stored as text) to a date column

This has been asked many times before and I tried quite a bit before posting this question. I have 2 columns on my SQL Server table where the dates are stored as CHAR(8) yyyymmdd format. When I try to insert this to another table with date column, I get:
Conversion failed when converting date and/or time from character string.
The typecasting that I used is:
,CAST(convert(char(10),qrda.BillFromDate,120) AS DATE) AS [BillStartDate]
,CAST(convert(char(10),qrda.BillToDate,120) AS DATE) AS [BillEndDate]
With the above code, I am trying to make it SQL Server readable date format and then typecasting it to DATE so that I can insert it to the destination table without any other transformations. Not sure where I am going wrong with this.
Since date are stored in the following format yyyyMMdd you can insert these values without any need to use CONVERT or CAST functions, since this format can be implicitly converted to DATE.
If the data contains invalid values such as 00000000, you can use TRY_CONVERT or TRY_PARSE function to convert these values to NULL
Example:
CREATE TABLE #TBLTEMP(datecolumn DATETIME)
INSERT INTO #TBLTEMP(datecolumn)
VALUES ('20180101')
INSERT INTO #TBLTEMP(datecolumn)
VALUES (TRY_PARSE('00000000' as DATETIME))
SELECT * FROM #TBLTEMP
Result:
From the example above, you can see that 20180101 was inserted succesfly without any casting, while TRY_PARSE function converted the invalid value 00000000 to NULL.
You can use the following syntax:
INSERT INTO TargetTable(DateColumn)
SELECT TRY_PARSE([CharColumn] as DATETIME
FROM SourceTable
References
Understanding SQL Server’s TRY_PARSE and TRY_CONVERT functions
TRY_PARSE (Transact-SQL)
Sorry for the trouble folks, but looks like this is bad production data where some values are literally '00000000'. I dont know how this flows into our system, but since the source table columns are CHAR(8), this is a valid value. Not so much for me.

Adding a date column and a nvarchar column together

I have 3 columns in my Test table that look like this
DATE TIME Combined
2015-08-17 16:07:49
2015-08-18 08:13:23
2015-08-18 08:13:24
2015-08-18 08:14:36
What I want to do is combine the Date and Time column to populate the Combined Column
The DATE column is actually a date Data Type.
The Time column is actually a nvarchar(MAX) Data Type.
I'm not exactly sure what to use for the Combined column.
Is it possible to add the two together as they are or do I have to convert the time and if so how do I do this conversion?
I have used:
alter table [dbo].[Test] alter column [TIME] time(0)
and have received this error message:
Conversion failed when converting date and/or time from character string.
Does anyone have have any insight for me on this and if I even need to convert it?
The data type for the combined column should be datetime2 (or datetime) as that is what it will hold.
You can't add a varchar value to a date type value, but to populate it you can cast the [date] column to a datetime and add the varchar string with the time part to it like this:
update dbo.test set combined = cast([date] as datetime) + [time] from dbo.test
This does however rely on the values in the [time] column being valid, and the error message you get indicates that some value(s) isn't, so you need to identify and correct those values first.
Example SQL Fiddle
for Display try,
select [Date]+' ' + Time as CombinedColumn from Test

Find a row with nvarchar column that have a int value between two values in middle of string in column

I have a nvarchar column that have values like
'21:15:00 monday 1390/09/10 morning'
I want to select rows that have a third part (meaning: '1390/09/10') between '1390/09/07' AND '1390/09/15'. I don't want to change the structure of column values to bring the third part to start or end of the string for some reasons. I tried this
SELECT * FROM table WHERE column BETWEEN '%1390/09/07%' AND '%1390/09/15%'
but it won't work.
I used SQL Server 2008.
To extract the date you have to do this:
DECLARE #t VARCHAR(100) ='21:15:00 monday 1390/09/10 morning'
SELECT CONVERT(DATETIME2, SUBSTRING(#t, PATINDEX('%[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]%',#t),10),111)
I used DateTime2 as I used SQL Server 2008.
I hope this help you.