I have three tables in database. I have the column Operation_Date in all of them. I set the column default value to (GETDATE()), and its data type is VARCHAR(50) and I don't have any coding in my C# Windows application that inserts value to Operation_Date.
Issue: When I insert rows to tables the operation_Date separates month, day and year with space like this (MAY 2 2020). I get two spaces after month and one space after days.
I tried to make a query on SQL Server to insert and the same problem occurs. I tried changing data type to datetime but with not success.
Note: this issue occurs only in two tables. And I am pretty sure the three tables have the same settings.
Is there anyway to force a certain date format for the default value in SQL Server? And what could make this issue happen?
This is the query I used:
USE [EasyManagementSystem]
INSERT INTO [dbo].[Attendance] ([Employee_No], [Present], [Leave], [Othe_Leave], [Month], [Year])
VALUES ('l-8068', 30, 0, 0, 'MAY', 2020)
Huh? Why would you be storing a date as a string. That is just wrong. There is a perfectly good data type for dates, called date.
If you want this to be set on input, then just give it a default value. Your table creation should look like:
create attendance (
. . .
operation_date date default getdate()
);
Voila! It will just work. If you want the month or year, you can use the month() and year() functions.
Related
I am using labview to query an SQL table, I am manipulating the data and inserting it into a new table. Two of the columns are datetime and can either be a date or a NULL but the format into string needs quotes ‘%s’ to insert the datetime or I get an error whereas the NULL will only insert when I have no quotes %s.
Is there an easy way to solve this for both? As I am sending in rows of about 30 columns and it is only when I come across a NUll in the datetime column that it errors?
Change your SQL query for the select to use an ifnull and return a date you know would be null. I would suggest the LabVIEW epoch of 1st January 1904 formatted to match whatever is normally in your database
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.
I set up a table yesterday with the following code. the code ran with no error messages reported and the table appeared correctly set up in object explorer.
Create Table PriceTable
(Airport_IACO_Code Varchar (4) NOT NULL,
Airline_IACO_Code Varchar (3) NOT NULL,
FlightDate Date NOT NULL Default Getdate(),
DepTime Time NOT NULL Default DATEADD(hour, 6, GETDATE()),
Price Smallmoney,
RouteDiscontinuedOrCommences Varchar (15),
)
GO
However on checking the table today the FlightDate which has the Getdate() default is showing yesterdays date
and
the the DepTime column which has the DateAdd Default is showing an incorrect time of 18:45:02. the current time as I am writing this is 11.04.
Does anyone know what is wrong.
Thanks in advance for any help offered.
You may find the handling of defaults a bit counter-intuitive in SQL Server. The syntax is:
DEFAULT constant_expression
It so happens that SQL Server extends the definition of constant_expression to include non-deterministic scalar functions, such as getdate(). These are functions that return a different value each time they are called, even with the same arguments. The definition in the documentation is:
Only a constant value, such as a character string; a scalar function
(either a system, user-defined, or CLR function); or NULL can be used
as a default.
However, SQL Server does not extend the definition to expressions of such functions. Instead, the expression is evaluated when the table is created and a constant value is inserted.
Unfortunately, one way to accomplish what you want is using a trigger. Alternatively, you could leave the value as NULL and create a computed column to calculate the date six hours hence:
create table . . .
_DepTime time,
DepTime as (cast(dateadd(hour, 6 _DepTime) as time) )
I am working on pulling some data in from a Rest-api into my MSSQL database. The issue I am having is the timestamp that I am being given from the api does not appear to be formatted correctly to just insert '2013-09-16T07:00:00+0000'.
example insert:
INSERT INTO [page_fan_adds_unique]([period], [title], [description], [value], [end_time])
VALUES ('day', 'Daily New Likes', 'Daily: The number of new people who have liked your Page (Unique Users)','0', '2013-09-16T07:00:00+0000')
I know changing the format to 2013-09-16T07:00:00+00:00 works but I didn't want to have to manipulate the data before the insert.
You cannot do this without formatting.
From the MSDN about TIMESTAMP:-
Is a data type that exposes automatically generated, unique binary
numbers within a database. timestamp is generally used as a mechanism
for version-stamping table rows. The storage size is 8 bytes. The
timestamp data type is just an incrementing number and does not
preserve a date or a time. To record a date or time, use a datetime
data type.
You may use datetime data instead.
This is what I did. from my PHP code I inserted that date [end_time] = CAST(STUFF('".."',23,3,':00')AS DATETIME2)"
Now when I write my "select" statements I just cast(end_time as datetime) I find that this is a lot easier than trying to cast a string into a datetime in sql.
How do i combine 2 column using SQL server 2005 ?
Problem is that The DateTime is stored in 1 column and the milliseconds is stored in another column.
I want to add the Milliseconds onto DateTime column to give it a more accurate DateTime.
I need to use this DateTime to query record accurate to milliseconds.
Any idea?
I need to replace DateTime with the added values.
SELECT *
FROM TABLENAME
WHERE [DateTime] >= '2011-04-12 12:00:00 AM'
AND [DateTime] <= '2011-05-25 3:35:04 AM'
and run the query.
Well, first solve your problem:
SELECT DATEADD(millisecond,<milliscolumn>,<datetimecolumn>) from <table>
And then file a bug report that these should just be stored in one column anyway.
You can do this, based on your sample query, but note that this destroys the possibility of the server being able to use an index:
SELECT * FROM TABLENAME WHERE
DATEADD(millisecond,[MillisecondColumn],[DateTime]) between
'2011-04-12T12:00:00' AND '2011-05-25T03:35:04'
If this is a large table, then indexes may be important. If you can't alter whatever's populating this data, you might want to add this calculation as a persisted computed column to this table, and then index and query against that.
Note that I've replaced your two comparisons with a single BETWEEN, and also adjusted the datetime strings so that they're not affected by regional settings.
SELECT (ColumnA + ColumnB) AS ColumnZ
FROM Table
might solve your problem.