使用SQL Server

时间:2017-11-30 05:14:10

标签: sql sql-server function tsql stored-procedures

我正在尝试将一些列从一个表移动到另一个表,在此过程中,我希望在插入另一个表之前将datetime列转换为日期和时间。为此,我正在使用存储过程来应用条件。但我无法适用条件。以下是我正在使用的表格。

dbo.Attendance

Id                                      UserId                                  Status  CheckIn             CheckOut            Date
---------------------------------------------------------------------------------------------------------------------------------------------
0083c28b-249e-4072-b6ac-822d7e4d2d35    5e397451-362f-4e1f-b257-0406fd8da3f8    Late    09:04:00.0000000    00:00:00.0000000    2017-01-16
0146da5c-0eae-4b4f-b9e6-2b5bffb34235    b3e0dc55-f738-478f-87ff-f52dae1f662a    Late    09:33:00.0000000    00:00:00.0000000    2017-01-24
023903d9-b6be-40fa-828e-83bee1748864    5e397451-362f-4e1f-b257-0406fd8da3f8    Full Day    08:45:00.0000000    00:00:00.0000000    2017-02-20
043030e5-fcc2-4409-b804-25fd5cce6a90    366c3918-8569-46ef-aa6c-d95e941bd255    Full Day    09:00:00.0000000    00:00:00.0000000    2017-03-13
05a15650-04c5-49f2-9476-046e15c4d917    b3e0dc55-f738-478f-87ff-f52dae1f662a    Late    09:13:00.0000000    00:00:00.0000000    2017-01-10
09f41fb0-6060-432f-91b6-c53be457f415    b3e0dc55-f738-478f-87ff-f52dae1f662a    Late    09:01:00.0000000    00:00:00.0000000    2017-01-21

dbo.UserActivity

DateTime                   UserId
----------------------------------------------------------------
2017-01-16 17:41:23.670    8c2d617b-8361-432a-9f19-0c70f81764fa
2017-01-31 08:59:22.093    3f8fc164-92e9-4714-a42c-8ae8a2f923a9
2016-09-30 11:41:41.100    da42b0f4-7d0b-4b68-ad81-12bea670c218
2017-01-20 14:19:10.613    8c2d617b-8361-432a-9f19-0c70f81764fa
2017-02-09 17:28:39.373    ac0ce1ad-f021-4fab-ab5e-9bbd48004a4b

查询

CREATE PROCEDURE abc1(@id uniqueidentifier)
AS
BEGIN
    DECLARE 

    INSERT INTO dbo.Attendence (Id, UserId, Date, CheckIn, CheckOut) 
        SELECT  
            Id = @id, UserId, Datetime AS dt, 
            DateTime AS chkin, DateTime AS chkout 
        FROM 
            dbo.UserActivity
END

我应该在哪里将datetime作为时间和日期分别转换为用户活动表中的日期,签入和结帐列以及Attendence表的ID?

2 个答案:

答案 0 :(得分:1)

您可以在手术中使用它。

INSERT INTO dbo.Attendence(Id,UserId, Date, CheckIn, CheckOut) 
SELECT 
    NEWID() AS Id
    , UserId
    , CAST([DateTime] AS DATE) as dt
    , CAST([DateTime] AS TIME) as chkin
    , CAST([DateTime] AS TIME) as chkout 
FROM dbo.UserActivity UA
WHERE NOT EXISTS
    ( SELECT * FROM dbo.Attendence A 
        WHERE A.UserId = UA.UserId 
            AND A.Date = CAST(UA.[DateTime] AS DATE) 
            AND A.CheckIn = CAST(UA.[DateTime] AS TIME)
            AND A.CheckOut = CAST(UA.[DateTime] AS TIME) )

答案 1 :(得分:0)

你可以用它。

val df = spark.read.option("header", "false").csv("file.txt")