用SQL在C#中创建Selecting MAX函数的方法
我有这种插入数据的方法用SQL在C#中创建Selecting MAX函数的方法,c#,sql-server-2008,C#,Sql Server 2008,我有这种插入数据的方法 private void InsertReceipt() { decimal Stub; Stub = Math.Floor(decimal.Parse(txtAmount.Text) / 2000); SqlCommand cmd = new SqlCommand(); cmd.Connection = cn; cmd.CommandType = CommandType.Te
private void InsertReceipt()
{
decimal Stub;
Stub = Math.Floor(decimal.Parse(txtAmount.Text) / 2000);
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Ticket(CustomerID, Date, Store, Amount, NoStub)" +
"VALUES (@CustomerID, @Date, @Store, @Amount, @NoStub) ";
cmd.Parameters.AddWithValue("@CustomerID", txtCustomerID.Text);
cmd.Parameters.AddWithValue("@Date", dtpDate.Value.Date.ToString());
cmd.Parameters.AddWithValue("@Store", txtStore.Text);
decimal amount = decimal.Parse(txtAmount.Text);
cmd.Parameters.AddWithValue("@Amount", amount);
cmd.Parameters.Add("@NoStub", SqlDbType.Decimal).Value = Stub;
cmd.ExecuteNonQuery();
}
我只想有一个方法,如果您在表“Ticket”中插入一个数据,那么另一个表将被更新
CustomerID Date Store Amount NoStub
1 6/7/2013 Nike 4000 2
2 6/7/2013 Adidas 6000 3
此表将被更新,例如,我将使用名为“StubRange”的表,此输出将被生成
RangeID CustomerID NoStub TickerStart TickerEnd
1 1 2 00001 00002
2 2 3 00003 00005
我只是想学习如何使用这种方法。当您在票证表中插入记录时,您需要编写一个插入触发器。您可以参考下面的语法来创建触发器。这是一种Oracle语法
CREATE OR REPLACE TRIGGER TRIGGER_INSERT_STUBRANGE
AFTER INSERT ON TICKET
FOR EACH ROW
DECLARE
raise_exception Exception;
BEGIN
--WRITE YOUR INSERT STATEMENT HERE
Exception
when raise_exception then
RAISE_APPLICATION_ERROR(-20001, sqlerrm );
END;
这将在更新table1时在table1上创建一个insert触发器,table2将使用CustomerID更新,表1中的NOSUB和其他属性取决于您的业务逻辑
CREATE TRIGGER trig_Update_table
ON [tableName1]
FOR INSERT
AS
Begin
Insert into tableName2 (CustomerID , NoStub)
Select Distinct i.CustomerID, i.NoStub
from Inserted i
End
您要查找的是插入后的
基本上,您可以将其视为在插入发生后触发的事件(因此触发…) 您的触发器应该类似于:
CREATE TRIGGER YourTriggerName --The name of your trigger
ON Ticket --The table it will be observing
AFTER INSERT,UPDATE --It will trigger after insert / update
AS
--The actions you want to do. For example:
DECLARE @CustomerId int
SET @CustomerId = (SELECT CustomerId FROM inserted) --you might want to use 'inserted' table
--Inset values
Insert into StubRange (CustomerID , NoStub)
Select Distinct ins.CustomerID, ins.NoStub
From Inserted ins
--Update existing records
UPDATE StubRange
set --Set what ever it is you want to update
WHERE CustomerId = @CustomerId
有关插入表格的详细信息-根据:
插入的表在插入期间存储受影响行的副本
和更新语句。在插入或更新事务期间,新建
行同时添加到插入表和触发器表中。这个
插入表中的行是触发器中新行的副本
桌子
插入触发器是你的朋友。先生,我只想有一种使用C#中代码的方法。我必须建议不要使用。如果你想保持数据的完整性,我会选择触发器。如果您坚持使用C#方法,那么是什么阻止您编写类似于您发布的更新“StubRange”并在每次调用“InsertReceive”时调用它的方法(根据定义,触发器会在插入后运行,并且它们是插入事务的一部分)呢