SQL Server Scope_Identity() 使用问题
我不明白为什么使用scope_identity() 的多表插入(存储过程)不起作用。这就是它的要点(请原谅这里缺乏想象力的命名):
TableB 的 RowID 列显然是一个int,没有设置为身份自动增量或类似的东西。
如果我在 Management Studio 中运行它,它会说 1 行受到影响,但它不会执行插入。
如果我从代码运行它,我会收到一条错误,指出我无法在 TableB、RowID 中插入 NULL 值,这是正确的,它具有非空约束。但它应该从第一个表中获取scope_identity()。
我已经在事务中和事务外以及各种参数初始化中尝试过了......这让我很沮丧。预先感谢您的任何帮助。
I can't figure out why this multi-table insert (stored procedure) using scope_identity() is not working. This is the gist of it (forgive the unimaginative naming here, please):
TableB's RowID column is obviously an int, not set as identity auto-increment or anything like that.
If I run it in management studio, it says 1 row was affected, but it does not do the inserts.
If I run it from code I get an error saying that I can't insert a NULL value in TableB, RowID, which is correct, it has a not null constraint. But it should be getting the scope_identity() from the first table.
I've tried it in and out of transactions and with various parameter initializations... It's killing me. Thanks in advance for any assistance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我假设 tableA 在数字列上设置了 IDENTITY?
如果不存在,则 SCOPE_IDENTITY() 将为 NULL
“受影响的 1 行”也不是来自此 INSERT 到表 A 中。
I assume tableA has an IDENTITY set on a number column?
SCOPE_IDENTITY() will be NULL if there isn't
The "1 row affected" isn't from this INSERT into tableA either.
您在此处显示的代码没有任何问题。我认为您在简化示例时已经删除了有问题的代码。
试试这个。
结果:
自己尝试一下。 https://data.stackexchange.com/stackoverflow/q/103697/使用范围标识
Nothing wrong with the code you have showed here. I think you have removed the problematic code when you simplified your sample.
Try this.
Result:
Take it for a spin yourself. https://data.stackexchange.com/stackoverflow/q/103697/using-scope-identity
另一件需要注意的事情是表上是否有触发器(尤其是 INSTEAD OF 触发器),这可能会导致记录无法插入。
在初始化 @newId 变量后,您可以添加一条 print 语句来查看它的值,看看它是否为 null 或者是否有值。
尝试使用显式事务和 try catch 块,然后您可以看到 catch 块中出现的错误(如果它没有通过第一个插入)。
One other thing to look at is whether you have a trigger (especially an INSTEAD OF Trigger)on the table which might be causing the record to not get inserted.
You can add a print statement to see the value of the @newId variable after you have initialized it to see if it is null or if it has a value.
Try using explicit transactions and a try catch block and then you can see what error you are getting in the catch block if it doesn't make it past the first insert.