插入多个与同一个表中的现有记录相同的新记录,其中一个列值已更改

时间:2013-04-22 05:58:57

标签: sql-server-2008 stored-procedures

我有一个表,我在其中存储属性的租约的记录。记录存储如下:

ID|PropertName|ContractStartDate|ContractEndDate|Status
 1| pqr     | 5/17/2012       | 5/17/2013     |leased
 2| xyz     | 10/25/2012      | 10/25/2013    |leased
 3| lmn     | 4/21/2012       | 4/21/2013     |leased   
 4| efg     | 4/22/2012       | 4/22/2013     |leased

现在我想写一个商店程序,它将检查ContractEndDate今天的日期,如果它已过期,则在数据库中添加新记录,其值与先前记录相同,但状态为已过期。

这是我的桌子在那之后应该怎么样的:

    ID|PropertName|ContractStartDate|ContractEndDate|Status
     1|   pqr     | 5/17/2012       | 5/17/2013     |leased
     2|   xyz     | 10/25/2012      | 10/25/2013    |leased
     3|   lmn     | 4/21/2012       | 4/21/2013     |leased   
     4|   efg     | 4/22/2012       | 4/22/2013     |leased
     5|   lmn     | 4/21/2012       | 4/21/2013     |expired
     6|   efg     | 4/22/2012       | 4/22/2013     |expired

我尝试关注此帖子:SQL to copy row and change 1 column value但是我在选择子查询时遇到语法错误。

我可以使用光标和触发器来解决这个问题吗?我对游标和触发器知之甚少,所以任何样本都会非常感激。感谢

3 个答案:

答案 0 :(得分:2)

DECLARE Cur CURSOR FOR
SELECT ID,PropertName,ContractStartDate,ContractEndDate,Status From TABLE_NAME

Open Cur
Declare @Id AS INT
DECLARE @PropertName AS VarChar(Max)
DECLARE @ContractStartDate AS DATETIME 
DECLARE @ContractEndDate AS DATETIME 
DECLARE @Status AS Varchar(80)
Fetch Next from Cur INTO @Id,@PropertName,@ContractStartDate,@ContractEndDate,@Status

While(@@fetch_status=0)
BEGIN
    IF(GETDATE() > @ContractEndDate)
    BEGIN
        DECLARE @newID bigint 
        set @newID = (select max(ID) FROM TABLE_NAME)
        INSERT INTO TABLE_NAME(ID,PropertName,ContractStartDate,ContractEndDate,Status)
        VALUES (@newID+1,@PropertName,@ContractStartDate,@ContractEndDate,'expired' )
        Fetch Next from Cur INTO @Id,@PropertName,@ContractStartDate,@ContractEndDate,@Status   
    END
    Fetch Next from Cur INTO @Id,@PropertName,@ContractStartDate,@ContractEndDate,@Status   
END

Close Cur
Deallocate Cur

答案 1 :(得分:1)

您可以使用光标解决此问题。

Step 1:  Open cursor with the select statement.(select * from table where ContractEndDate = sysdate)
Step 2: Loop the cursor
        Insert the values as 
        insert into table (ID,PropertName,ContractStartDate ,ContractEndDate,Status) values (newid, cursorVariable.PropertName,... , 'expired');

Step 3: End of the loop / with in the loop commit the transaction.

答案 2 :(得分:1)

您可以INSERT ..... SELECT。假设您的IDIDENTITY列。

INSERT INTO TABLE1(PropertName,ContractStartDate,ContractEndDate,Status)
SELECT PropertName, ContractStartDate, ContractEndDate, 'expired' 
FROM TABLE1 
WHERE GETDATE() > CONTRACTENDDATE

SQL FIDDLE DEMO