开发者

SQL Server - compound statements

I'm working on a project in C#, and am executing开发者_如何学Python this statement, but not getting back anything (using a datatable to get data back)

string SQL = 
  "DECLARE @NewID int; SELECT TOP 1 @NewID = [ItemID] + 1 FROM [GroupItems] ORDER BY [ItemID] DESC; " + 
  "INSERT INTO [GroupItems] ([InstanceID], [ItemID], [GroupID], [ItemName], [DisplayName], [Units], [Updated]) " +
  "VALUES(@instanceID, @NewID, @groupID, @name, @display, @units, CURRENT_TIMESTAMP); SELECT * FROM [GroupItems] WHERE [ItemID]=@NewID";

Basically what I want to do is return the row I just created. Any help?


  • You are probably missing information because of the @variables being NULL. How do you set them?
  • Are suppressing errors somehow.
  • Do you get data stored in the table, or just no results?

Anyway, there are easier ways to do this in one line

First off, make the ItemID column an IDENTITY. Otherwise this code will fail at some point because it isn't safe for overlappping calls

Then second, change the code to use the OUTPUT clause. You can do this in one go

INSERT INTO [GroupItems] ([InstanceID], [GroupID], [ItemName], [DisplayName], [Units], [Updated])
OUTOUT INSERTED.*
VALUES(@instanceID, @groupID, @name, @display, @units, CURRENT_TIMESTAMP);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜