INSERT的存储过程不起作用

时间:2014-01-07 18:30:58

标签: sql sql-server sql-server-2008 stored-procedures sql-insert

在这里,您可以在SQL中看到我的代码表,存储过程正在运行,但行中没有填充信息。代码有什么问题?

CREATE TABLE Category_Master(
    Category_ID INT IDENTITY(1,1) PRIMARY KEY,
    Category_Name VARCHAR(50),
    modification_Date DATETIME DEFAULT GETDATE()
)

Select * from Category_Master
Go

create trigger TRIGGER_MODIFDATE_Category_Master
on Category_Master
for insert, update 
as begin 
    UPDATE Category_Master 
    SET modification_Date = GETDATE()
end 
Go

CREATE PROCEDURE usp_InsertCategory_Master
    @flag bit output,-- return 0 for fail,1 for success
    @Category_ID int,
    @Category_Name varchar(50)
AS
BEGIN
  BEGIN TRANSACTION 
  BEGIN TRY 
       INSERT INTO Category_Master(Category_ID, Category_Name) 
       VALUES (@Category_ID, @Category_Name)

       SET @flag = 1;

       IF @@TRANCOUNT > 0
       BEGIN 
           COMMIT TRANSACTION;
       END
  END TRY 
  BEGIN CATCH
       IF @@TRANCOUNT > 0
       BEGIN 
          ROLLBACK TRANSACTION;
       END

       SET @flag = 0;
  END CATCH
END 
Go

Declare @flag bit

EXEC usp_InsertCategory_Master @flag output, 1, 'Short LOAN'
EXEC usp_InsertCategory_Master @flag output, 2, 'Long LOAN'

if @flag=1
  print 'Successfully inserted'
else
  print 'There is some error' 

1 个答案:

答案 0 :(得分:2)

您无法将值插入标识列。您不会在其中输入任何内容,它会自动填充值。您的代码因此而失败。

如果您确实希望能够这样做,请按以下方式定义列:

Category_ID INT UNIQUE PRIMARY KEY

或者您可以在插入期间禁用标识列:

http://technet.microsoft.com/en-us/library/aa259221%28v=sql.80%29.aspx