这是一个确切的查询吗?

时间:2012-01-31 09:30:56

标签: c# sql winforms

我有两张桌子

Inbox(id,accountid,emailfrom,emailsubject,emailbody,emaildate,attachment)
Trash(as above)

当用户想要从inboxDataGridView删除行时,首先将该行复制到trash表。我尝试此查询首先复制行:

string query = "INSERT INTO Trash(inboxid, accountid, emailfrom, subject, emailbody,emaildate,attachment) SELECT inboxid, accountid, emailfrom, subject, emailbody,emaildate,attachment FROM Inbox WHERE(inboxid = " + accountinfo.PEmailId + ")";(where accountinfo.PEmailId = selectedRow value

但是这个查询给了我一个错误。

请指导我如何做,复制和删除。

2 个答案:

答案 0 :(得分:1)

这应该有效:

插入:

INSERT INTO Trash(id, accountid, emailfrom, subject, emailbody,
   emaildate,attachment)
SELECT id, accountid, emailfrom, subject, emailbody,emaildate,attachment 
FROM Inbox 
WHERE id = @id

删除:

DELETE Inbox
WHERE id = @id

您需要执行语句in the same command或两个单独的命令within a transaction,具体取决于您是否要在其中执行其他操作。 @id参数应作为命令参数提供,以便prevent SQL injection attacks

如果您想在数据库端部分解决方案,可以将其创建为存储过程,或者as @ThitLwinOo suggests创建触发器。如果您正在使用触发器方法,则删除语句足以从您的程序执行。

答案 1 :(得分:0)

实际上有一种简单而更好的方法可以通过在delection上编写触发器来完成你想要的东西。什么是你的DB? SQL Server?

我假设您的数据库是Sql Server ..请在ur db中尝试以下触发器。


CREATE TRIGGER [dbo].[tri_BACKUP_DELETED_ROWS] 

ON [dbo].[Inbox]

AFTER DELETE

AS 

BEGIN

    SET NOCOUNT ON;

    -- Insert statements for trigger here
    IF EXISTS (SELECT * FROM deleted)
    BEGIN
        -- keep old record
        INSERT INTO Trash(inboxid, accountid, emailfrom, subject, emailbody,emaildate,attachment)       
        SELECT inboxid, accountid, emailfrom, subject, emailbody,emaildate,attachment 
        FROM DELETED
    END

END