SQL Server 2008R2 alter GETDATE result as a default value - sql-server

Is there a way to alter the outcome of getdate() while still using it as a default value? E.g. being able to plus or minus x number of hours.
The situation:
a German hosted server (GMT+2) with some end users in Australia (GMT+10). One column is using the default getdate() value therefore is inserting German time. Some code is generating a DateTime based on Australia time so there are 8 hours difference.
The objective:
For several good reasons the aim is to handle this on the database and not touch application code. I would like to add 8 hours onto the German getdate() default database value....... or handle this some other way on the database

you can use default value using DATEADD() function to add 8 hours to the date:
create table dbo.foo
(
dateColumn datetime default (dateadd(hour,8,getdate()))
)

I don't see any such option and it is little dangerous too. You can create a function with the same name GETDATE in your database, but that would require you to prefix with dbo(or schema name) while calling the function.
So, you may need to write your own function and make use of GETUTCDATE() and add delta according to timezone.

Related

PB Select TODAY() Into :var From DUMMY

When I get TODAY in SELECT in PB, it returns 1900/1/1
date var
Select TODAY() Into :var From DUMMY
But when I assign to variable TODAY(), it works as expected
date var
var = today()
I use MS SQL Server 2016 and PowerBuilder 12.5.
I've supposed that the problem is in different date formats, but I have changed date format at my Windows locale in the way, that PB TODAY() returns 2018-10-08 and MSSQL GetDate() returns 2018-10-08 18:25:23.207
So date parts have the same formats.
The problem is not in DUMMY table since I have created MS SQL DUMMY table and inserted 1 row in it.
Also I'm wondering if there are any difference in SELECT TODAY() and var = TODAY()?
I suppose that 1st variant returns MS SQL server time but 2nd returns local time. Is not is?
Try below SQL.
Select getdate() into :var From DUMMY;
You provided your own answer: Today() is a PowerScript function, GetDate() is the function on MS SQL. If you’re executing SQL, it needs to be a valid SQL statement for the server you’re executing against (except for the INTO :var part), and can’t include a PowerScript function.
Two other things:
“FROM DUMMY” is an Oracle thing, and I’m pretty sure it won’t work on MS. (You’re capturing your error codes after executing the SQL, right?)
I won’t say this is likely a critical problem, but as you point out, GetDate returns a datetime; I’d recommend that as your data type for the capture variable.
And yes, GetDate() will be your server’s date/time, Today() will be based on the local workstation.
Good luck.

Issue with Datetime in SQL Server 2008

I am importing some data from excel to db, the issue is I want to set the specific default value like 00/00/0000 to datetime column when there is no date available from the Excel file.
The getdate() sets the date to current one, but I want to set to a specific date, is it possible to achieve something like this.
Sure you can set a default value - but be aware: DATETIME has a valid range from 1/1/1753 through 12/31/9999 - so setting it to 0/0/0000 will NOT be a valid DATETIME value!
If you need such a value - use either DATETIME2 in SQL Server 2008 (range is from 1/1/0001 through 12/31/9999) - or use DATE (without any time - same range as DATETIME2)
Or: just make your DATETIME/DATETIME2/DATE column nullable and insert NULL when no date is present - that would be the cleanest solution.
When you use bcp or BULK INSERT or SQLBulkCopy, then you have the option of keeping NULLs.
If you don't, then you get the default for the column.
See "Keeping Nulls or Using Default Values During Bulk Import" on MSDN
If you can't (say because you get empty string not NULL) then you can use a a staging table first, then load the data from that with a combination of NULLID, ISNULL and CASE. Or use a trigger, but this will slow you down more so than doing the load in 2 steps
I'm not sure how you are performing your import, but if you wish to check whether a value is NULL and set it to a defined value then you can use the SQL IsNull(a,b) where a is the value to check and b is the value to return.
insert into [dbo].[tblSomeTable]
set [someField] = IsNull(#thisValueMayBeNull, thisValueIfNull)
Probably not a good example but should point you in the right direction.
Or once your data has been imported you could run an update script to replace all NULL dates with a fixed value;
Or you could set the date field in the database to NOT NULL and give it a defaut value.

Simulate current date on a SQL Server instance?

Is it possible to change the datetime for a particular database on SQL Server?
Is it tied to the operating system's date/time?
We wish to simulate a future datetime for testing purposes i.e. so the GETDATE() returns a date in the future.
It's got to be in a semi-production (staging) environment so unfortunately changing the OS date / time isn't an option for us.
In an ideal world we'd spin up a virtual server, but also not really an option at the moment.
As stated, by others, No.
A really hacky workaround, would be be to write your own function to return the date you want and have it return GETDATE() when you're done testing, and call that function instead. There's probably some slight overhead in doing this, but it'll do what you need.
Unfortunately it is tied to the OS date and time. See here: http://msdn.microsoft.com/en-us/library/ms188383.aspx
This value is derived from the operating system of the computer on
which the instance of SQL Server is running.
You can always use this and adjust accordingly:
SELECT getutcdate()
Please see below for more information
StackOverflow Question
But there is no way to change the results from a GETDATE() without changing the server's date.
Added:
You could do a EXEC xp_cmdshell 'DATE 10/10/2011' if you wish... but it's not advised.
Another workaround I've had some success with is to add an INSTEAD OF trigger to any table where a GETDATE() value is being inserted and modify it there e.g.:
ALTER TRIGGER [dbo].[AccountsPayableReceivable_trg_i] ON [dbo].[AccountsPayableReceivable]
INSTEAD OF INSERT
AS
SET NOCOUNT ON
SELECT *
INTO #tmp_ins_AccountsPayableReceivable
FROM INSERTED
UPDATE #tmp_ins_AccountsPayableReceivable
SET dtPaymentMade = '01-Jan-1900'
WHERE dtPaymentMade between dateadd(ss, -5, getdate()) and dateadd(ss, +5, getdate())
INSERT INTO AccountsPayableReceivable
SELECT *
from #tmp_ins_AccountsPayableReceivable
(Incidentally, the where clause is there because my test script autogenerates these triggers, adding an update for every datetime column, so I only want to update those that look like they are being inserted with a GETDATE() value.)
I believe you can create a user function that would do the calculation for you and apply that.
http://msdn.microsoft.com/en-us/library/ms186755.aspx
Also, it can be used as the default value for a column.
Bind a column default value to a function in SQL 2005

Changing the output of Getdate

Is it possible to deceive SQL Server to return a different date on GetDate() without actually changing the machine date?
This would be great, since we have a database with old data and I'm trying to test some queries that use getdate().
I can change my machine date but that brings some other problems with other applications...
Any tips?
Thanks!
According to the documentation for getdate():
This value is derived from the
operating system of the computer on
which the instance of SQL Server is
running.
Since it's derived from the OS, I don't think you can change it separately.
You can always wrap GetDate() in a custom function and use that everywhere, although it's not an optimal solution.
No, there is not much you can do other than something like this:
SELECT GETDATE()-7 --get date time 7 days ago
SELECT DATEADD(dd, -7, GETDATE())
One approach is to have an optional fake clock.
Create a single row table (I usually call it dbo.System cos I usually have a number of global parameter values) with a column I call mine CurrentMoment which is datetime2 NULL (so the value can be NULL or a datetime).
Create a function to replace GetDate()
CREATE OR ALTER FUNCTION [dbo].GetDate
RETURNS datetime2
AS
BEGIN
RETURN ISNULL((SELECT CurrentMoment FROM dbo.System), SYSDATETIME());
END
GO
-- Yes the above returns a more accurate clock than GETDATE().
Replace ALL references to GETDATE() with dbo.GetDate() - This does require a small change to existing scripts.
With System.CurrentMoment set to NULL all works as normal, real time. But set a value and you have a fake clock, you have to update it as tests/demo proceed.
If you are concerned about performance, you can modify the function so it either returns SYSDATETIME() or the fake datetime as preferred. But I have not found a performance issue worth worrying about.
Alternatively you could have a column in System which is an offset to the current time, and subtract it from SYSDATETIME() when the function is called. That way the value will move on between function calls.

Change default date time format on a single database in SQL Server

I need to change the date format from US (mm/dd/YYYY) to UK (dd/mm/YYYY) on a single database on a SQL server machine.
How can this be done?
I've seen statements that do this for the whole system, and ones that do it for the session, but I can't change the code now as it will have to go through QA again, so I need a quick fix to change the date time format.
Update
I realize that the date time has nothing to do with how SQL Server stores the data, but it does have a lot to do with how it parses queries.
I'm chucking raw data from an XML file into a database. The dates in the XML file are in UK date format.
You could use SET DATEFORMAT, like in this example
declare #dates table (orig varchar(50) ,parsed datetime)
SET DATEFORMAT ydm;
insert into #dates
select '2008-09-01','2008-09-01'
SET DATEFORMAT ymd;
insert into #dates
select '2008-09-01','2008-09-01'
select * from #dates
You would need to specify the dateformat in the code when you parse your XML data
In order to avoid dealing with these very boring issues, I advise you to always parse your data with the standard and unique SQL/ISO date format which is YYYY-MM-DD. Your queries will then work internationally, no matter what the date parameters are on your main server or on the querying clients (where local date settings might be different than main server settings)!
You can only change the language on the whole server, not individual databases. However if you need to support the UK you can run the following command before all inputs and outputs:
set language 'british english'
Or if you are having issues entering datatimes from your application you might want to consider a universal input type such as
1-Dec-2008
Although you can not set the default date format for a single database, you can change the default language for a login which is used to access this database:
ALTER LOGIN your_login WITH DEFAULT_LANGUAGE=British
In some cases it helps.
If this really is a QA issue and you can't change the code. Setup a new server instance on the machine and setup the language as "British English"
Use:
select * from mytest
EXEC sp_rename 'mytest.eid', 'id', 'COLUMN'
alter table mytest add id int not null identity(1,1)
update mytset set eid=id
ALTER TABLE mytest DROP COLUMN eid
ALTER TABLE [dbo].[yourtablename] ADD DEFAULT (getdate()) FOR [yourfieldname]
It's working 100%.
You do realize that format has nothing to do with how SQL Server stores datetime, right?
You can use set dateformat for each session. There is no setting for database only.
If you use parameters for data insert or update or where filtering you won't have any problems with that.
For SQL Server 2008 run:
EXEC sp_defaultlanguage 'username', 'british'

Resources