sql server插入if语句

时间:2013-08-06 15:30:10

标签: sql sql-server if-statement insert

如果date_start(类型为datetime)在过去,我试图插入一行,而date_start + duration(type; real)(获取结束日期。)是将来。我不断得到子查询返回的多个结果。

IF  (CAST(CONVERT(datetime,(SELECT date_start FROM [tableA])) as float)- CAST(CONVERT(datetime,CURRENT_TIMESTAMP) as float))<0 
AND 
(24*(CAST(CONVERT(datetime, (SELECT date_start FROM [tableA])) as float)- CAST(CONVERT(datetime,CURRENT_TIMESTAMP) as float)) + (SELECT duration FROM [tableA]))>0
BEGIN
        INSERT INTO [tableB](col1) 
    select 24*(CAST(CONVERT(datetime,date_start) as float)- CAST(CONVERT(datetime,CURRENT_TIMESTAMP) as float))  FROM [tableA]
END

知道我该怎么做?

3 个答案:

答案 0 :(得分:1)

那是因为这个:

SELECT duration FROM [tableA]

我非常确定你的错误需要过滤,以便返回一行。

答案 1 :(得分:1)

@Fearghal你应该试试这个 -

DECLARE @required_date DATETIME
DECLARE @duration REAL

DECLARE date_cursor CURSOR FOR
SELECT date_start, duration FROM [tableA]

OPEN date_cursor
FETCH NEXT FROM date_cursor
INTO @required_date, @duration 
WHILE @@FETCH_STATUS = 0
BEGIN
    IF  (CAST(@required_date as float)- CAST(CONVERT(datetime,CURRENT_TIMESTAMP) as    float))<0 
AND 
(24*(CAST(@required_date as float)- CAST(CONVERT(datetime,CURRENT_TIMESTAMP) as float)) + @duration)>0
    BEGIN
         INSERT INTO [tableB](col1) 
         select 24*(CAST(CONVERT(datetime,date_start) as float)- CAST(CONVERT(datetime,CURRENT_TIMESTAMP) as float))  FROM [KAP_db_C4].[dbo].[PM]
    END
FETCH NEXT FROM date_cursor
INTO @required_date, @duration
END
CLOSE date_cursor
DEALLOCATE date_cursor

答案 2 :(得分:0)

好吧,我想我得到了....如果我错了,请纠正我,但不需要光标和变量。我最终得到了这个。我不能用ya,欢呼来完成它

INSERT INTO [TABLEB](col1,........, col6) 
         select 24*(CAST(CONVERT(datetime,date_start) as float)- CAST(CONVERT(datetime,CURRENT_TIMESTAMP) as float)), ENTITY, 'PM', NULL, NULL, NULL, NULL, '0'  FROM [TABLEA] 
            where (CAST(CONVERT(datetime,date_start) as float)- CAST(CONVERT(datetime,CURRENT_TIMESTAMP) as float))<0 
            AND 
            (24*(CAST(CONVERT(datetime,date_start) as float)- CAST(CONVERT(datetime,CURRENT_TIMESTAMP) as float)) + duration)>0