How do I specify date literal when writing SQL query from SQL Server that is linked to Oracle?

前端 未结 3 661
-上瘾入骨i
-上瘾入骨i 2020-12-01 19:03

I have a SQL Server 12.0 database that is linked to an Oracle 12.1 database.

I want to create a view in the SQL Server database that returns data from an Oracle tabl

相关标签:
3条回答
  • 2020-12-01 19:38

    If the query is running on Oracle database, then I suggest use the ANSI date literal which uses a fixed Format YYYY-MM-DD.

    For example,

    DATE '2015-10-20'
    

    In Oracle, '20140701' is a string and not a DATE. You might just be lucky to see an implicit data type conversion and get the result based on the locale-specific NLS settings of your client. You should always avoid it, and explicitly convert the string into date for date comparisons.

    0 讨论(0)
  • 2020-12-01 19:41

    I would recommend using the full ISO 8601 format as suggested by @lad2025:

    '2017-10-06T14:57:23'
    

    This is superior to the ODBC format suggested by @Shnugo.

    In SQL Server 2014 at least, the ODBC format will not work for dates prior to 1753-01-01 (e.g. those dates outside of the range of the old DATETIME data type), whereas the ISO 8601 format does.

    To test this yourself, try the following queries:

    --This will work
    DECLARE @DateISO DATE = '0001-01-01T00:00:00';
    SELECT @DateISO;
    
    --This will also work
    DECLARE @DatetimeISO DATETIME2 = '0001-01-01T00:00:00';
    SELECT @DatetimeISO;
    
    --This will not work
    DECLARE @DateODBC DATE = {D '0001-01-01'};
    SELECT @DateODBC;
    
    --This will also not work
    DECLARE @DatetimeODBC DATETIME2 = {ts '0001-01-01 00:00:00'};
    SELECT @DatetimeODBC;
    

    Even if you don't think the dates you're working with will ever be before the year 1753, it's a good habit to be in. I ran into this while looking at setting up a calendar table to reference in queries.

    0 讨论(0)
  • 2020-12-01 19:50

    I prefer the ODBC format:

    --DateTime
    SELECT {ts'2015-09-20 12:30:00'}
    --Time (however this comes with "today"-time)
    SELECT {t'12:30:00'}
    --Date
    SELECT {d'2015-09-20'}
    GO
    

    The simple date literal is not culture independent...

    SET LANGUAGE ENGLISH;
    SELECT CAST('2014-09-13' AS DATETIME);
    GO
    SET LANGUAGE GERMAN;
    SELECT CAST('2014-09-13' AS DATETIME);--ERROR: there's no month "13"
    GO
    

    But it works - however - with target type DATE (this difference is rather weird...):

    SET LANGUAGE ENGLISH;
    SELECT CAST('2014-09-13' AS DATE);
    GO
    SET LANGUAGE GERMAN;
    SELECT CAST('2014-09-13' AS DATE);--ERROR: there's no month "13"
    GO
    

    Thx to lad2025 I want to add for completness the "full" ISO 8601, which works fine:

    SET LANGUAGE ENGLISH;
    SELECT CAST('2014-09-13T12:30:00' AS DATETIME);
    GO
    SET LANGUAGE GERMAN;
    SELECT CAST('2014-09-13T12:30:00' AS DATETIME);
    GO
    
    0 讨论(0)
提交回复
热议问题