SQL Server Cannot Call Methods on Date

后端 未结 11 1453
时光取名叫无心
时光取名叫无心 2020-12-16 10:41

I\'ve got a DATETIME column in a SQL Server 2008 table called ShiftDate. I want to convert this to a DATE column in a query:

SELECT     ID, ScheduleID, Shift         


        
相关标签:
11条回答
  • 2020-12-16 11:08

    You can create a function and use that when you need to convert a DATETIME to DATE.

    USE [MyDatabaseName]
    GO
    
    IF EXISTS (
      SELECT * 
        FROM sys.objects 
       WHERE object_id = OBJECT_ID(N'[dbo].[FN_DateFromDateTime]')
       and  type in (N'FN')
    )
       DROP FUNCTION [dbo].[FN_DateFromDateTime]
    GO
    
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    -- =============================================
    -- Author:      Codestalker
    -- Create date: Mar 17, 2017
    -- Edited date: Mar 17, 2017
    -- Description: Return Date from DateTime.
    -- =============================================
    CREATE FUNCTION [dbo].[FN_DateFromDateTime]
    (
        -- Add the parameters for the function here
        @InputDateTime DateTime
    )
    RETURNS Date
    AS
    BEGIN
            DECLARE @ReturnDate Date
            Set @ReturnDate = CONVERT(DATE, @InputDateTime)  
            Return @ReturnDate
    END   
    GO
    

    Then in your view call the function to convert your DATETIME.

    SELECT DateTimeColumn, dbo.FN_DateFromDateTime(DateTimeColumn) AS ConvertedDateTime
    FROM dbo.MyTable
    

    You will not get the error message and it is reusable. (Tested in SQL Server 2012)

    0 讨论(0)
  • 2020-12-16 11:10

    Sometimes this works...

    CAST(CAST(YourDate AS char(10)) AS Datetime)
    

    (Yes I know it is not Date, but it is one step closer)

    In the same query, it worked in the outside select, but not inside the union all...

    Don't ask why :P

    0 讨论(0)
  • 2020-12-16 11:14

    I can assume that (ShiftDate AS DATE) should have a datetime format. If you try this:

    CAST(CONVERT(DATE, ShiftDate) as Varchar)

    0 讨论(0)
  • 2020-12-16 11:14

    This problem is still present in SSMS 18.4. I just sent it to Microsoft as an "idea", and since Microsoft's attention to every given bug report depends (only) on the social support of it, if you want it fixed, please go and vote for it at

    https://feedback.azure.com/forums/908035-sql-server/suggestions/41135050-ssms-returns-error-on-valid-query-in-view-designer

    0 讨论(0)
  • 2020-12-16 11:15

    This also happens when you mistakenly put the column multiple times after tablename.

    Suppose TableName is Person and column is Age

    and you have written in query like:

    Person.Age.Age = 30
    

    Hope my experience will help someone.

    0 讨论(0)
提交回复
热议问题