0

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

(1) 对于 Select 语句:

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

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

我怎样才能做到这一点?请帮我。

谢谢!

4

2 回答 2

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 
于 2013-11-08T15:13:22.127 回答
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';
于 2013-11-08T15:42:05.833 回答