简体   繁体   中英

How can I create a stored procedure which takes values from a table and insert them into new table

如何在SQL中创建一个存储过程,该存储过程接受表中的名称,区域,开始日期,结束日期作为输入,并在开始日期和结束日期之间的每个日期将名称,区域和日期插入到表中(具有3列名称,区域,日期)。

This is not possible. You cannot perform DDL and DML operations in functions in SQL Server.

As Gordon suggested, you need to use a stored procedure to achieve this.

Here is an example to start with

http://www.sqlinfo.net/sqlserver/sql_server_stored_procedure_INSERT.php

DECLARE @name NVARCHAR(20) = 'name';
DECLARE @area NVARCHAR(20) = 'area';
DECLARE @startDate DATE = '2016-11-30';
DECLARE @endDate DATE = '2016-12-30';

DECLARE @currentDate DATE = @startDate;

SELECT
    @currentDate AS Date
INTO
    #dates;

WHILE(@currentDate < @endDate)
    BEGIN
        SET @currentDate = DATEADD(d, 1, @currentDate);
        INSERT INTO #dates
        VALUES( @currentDate);
    END;

SELECT
    @name,
    @area,
    *
FROM
    #dates;

You can get variables as parameter and use the last select statement to create your new table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM