0

我有一个表,我在其中存储有关属性的租赁合同的记录。记录的存储方式如下:

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但我收到选择子查询的语法错误。

我可以使用光标和触发器解决这个问题吗?我对游标和触发器知之甚少,因此将不胜感激任何样本。谢谢

4

3 回答 3

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
于 2013-04-23T07:29:49.773 回答
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.
于 2013-04-22T06:14:07.417 回答
1

你可以简单INSERT...... SELECT假设你ID是一IDENTITY列。

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

SQL 小提琴演示

于 2013-04-22T06:55:37.757 回答