从SINGLE SELECT语句中插入多个数据(SQL)

时间:2013-11-08 15:06:17

标签: sql sql-server date

我正在尝试从SQL Server 2008中的单个select语句插入多个数据。

(1)对于Select Statement:

CREATE PROCEDURE getAllDaysBetweenTwoDate
(
@StartDate DATETIME,    
@EndDate DATETIME
)
AS
BEGIN

DECLARE @TOTALCount INT
SET @StartDate = DATEADD(DAY,-1,@StartDate)
Select  @TOTALCount= DATEDIFF(DD,@StartDate,@EndDate);

WITH d AS 
        (
          SELECT top (@TOTALCount) AllDays = DATEADD(DAY, ROW_NUMBER() 
            OVER (ORDER BY object_id), REPLACE(@StartDate,'-',''))
          FROM sys.all_objects
        )
    SELECT AllDays From d
RETURN 
END
GO

- 使用此代码,我可以获取两个日期之间的日期,即StartDate和EndDate。

(2)我试图将日期插入另一个表格。

例如

@StartDate = 2013-11-05
@EndDate = 2013-11-08

结果将是ff:

2013-11-05,
2013-11-06,
2013-11-07,
2013-11-08

我想将这些日期插入另一个表格。

我该怎么做?请帮帮我。

谢谢!

2 个答案:

答案 0 :(得分:3)

尝试:

INSERT INTO MyTable 
EXECUTE getAllDaysBetweenTwoDate @StartDate = '2013-11-05', @EndDate = '2013-11-08';

编辑:(插入'1'常量)

DECLARE @t table ([date] datetime)

INSERT INTO @t ([date])
EXECUTE getAllDaysBetweenTwoDate @StartDate = '2013-11-05', @EndDate = '2013-11-08';

INSERT INTO MyTable (DateColumn, Number1Column)
SELECT [date], '1' FROM @t 

答案 1 :(得分:1)

根据您的评论,您尝试插入常量值和日期。更改您的代码以执行此操作

CREATE PROCEDURE getAllDaysBetweenTwoDate
(
@StartDate DATETIME,    
@EndDate DATETIME
)
AS
BEGIN

DECLARE @TOTALCount INT
SET @StartDate = DATEADD(DAY,-1,@StartDate)
Select  @TOTALCount= DATEDIFF(DD,@StartDate,@EndDate);

WITH d AS 
        (
          SELECT top (@TOTALCount) AllDays = DATEADD(DAY, ROW_NUMBER() 
            OVER (ORDER BY object_id), REPLACE(@StartDate,'-',''))
          FROM sys.all_objects
        )
    SELECT AllDays, 1 As Leave From d
RETURN 
END

GO

然后这样做

INSERT INTO tblAttendance2 (DateTimeIn, Leave) 
EXEC getAllDaysBetweenTwoDate 
   @StartDate = '2013-11-05', 
   @EndDate = '2013-11-08';

如果您想返回用户ID,请尝试此

CREATE PROCEDURE getAllDaysBetweenTwoDate
(
@StartDate DATETIME,    
@EndDate DATETIME,
@userid varchar(100)
)
AS
BEGIN

DECLARE @TOTALCount INT
SET @StartDate = DATEADD(DAY,-1,@StartDate)
Select  @TOTALCount= DATEDIFF(DD,@StartDate,@EndDate);

WITH d AS 
        (
          SELECT top (@TOTALCount) AllDays = DATEADD(DAY, ROW_NUMBER() 
            OVER (ORDER BY object_id), REPLACE(@StartDate,'-',''))
          FROM sys.all_objects
        )
    SELECT AllDays, 1 As Leave, @userid As userId From d
RETURN 
END

GO

然后这样做

INSERT INTO tblAttendance2 (DateTimeIn, Leave, UserId) 
EXEC getAllDaysBetweenTwoDate 
   @StartDate = '2013-11-05', 
   @EndDate = '2013-11-08',
   @UserId = 'xyz';