Insert into view returns 2 rows affected
In Sql Server 2005, I have two databases. In the first one I have a table开发者_运维知识库 like this:
CREATE TABLE [dbo].[SG](
[id] [int] IDENTITY(1,1) NOT NULL,
[sgName] [nvarchar](50) NOT NULL,
[active] [bit] NOT NULL,
[hiddenf] [int] NOT NULL
)
In the second, I have a view like this:
CREATE VIEW [dbo].[SG] AS
SELECT id,sgName, active
FROM [FirstDatabase].dbo.SG WHERE hiddenf = 1
with a trigger like this:
CREATE TRIGGER [dbo].[InsteadTriggerSG] on [dbo].[SG]
INSTEAD OF INSERT AS BEGIN
INSERT INTO [FirstDatabase].dbo.SG(sgName,active,hiddenf)
SELECT sgName,COALESCE (active,0), 1 FROM inserted
END
When I insert into the view:
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand("INSERT INTO SG(sgName, active) VALUES('Test', 1)", connection);
var affectedRows = command.ExecuteNonQuery();
Assert.AreEqual(1, affectedRows);
}
I get affectedRows equal to two, while my expected value is 1.
This sort of question usually makes me think "triggers".
I have just created an exact copy of your scenario (thanks for the detailed instructions) and I am kind of seeing similar results.
By kind of, I meant that when I execute the insert, SSMS outputs
(1 row(s) affected)
(1 row(s) affected)
but when I checked the original database, only one row had been added.
To solve your problem, do this:
ALTER TRIGGER [dbo].[InsteadTriggerSG] on [dbo].[SG]
INSTEAD OF INSERT AS BEGIN
SET NOCOUNT ON -- adding this in stops it from reporting from in here
INSERT INTO [TEST].dbo.SG(sgName,active,hiddenf)
SELECT sgName,COALESCE (active,0), 1 FROM inserted
END
The issue is that both the trigger and the actual table on the original database are reporting that they've updated a row. If you remove this reporting from the trigger, but leave it in the original database, you will always get a true answer, whether you update via the view or straight into the original table directly.
精彩评论