【发布时间】:2018-05-17 08:08:12
【问题描述】:
目前我正在尝试在 SQL Server 中创建一个存储过程。
这是我的存储过程:
CREATE PROCEDURE sp_MasterManagement
@ProductId INT,
@ProductName NVARCHAR(40),
@SupplierID INT,
@CategoryID INT,
@QuantityPerUnit NVARCHAR(20),
@UnitPrice DECIMAL(10, 5),
@UnitsInStock SMALLINT,
@UnitsOnOrder SMALLINT,
@ReorderLevel SMALLINT,
@Discontinued BIT,
@StatementType VARCHAR
AS
BEGIN
IF @StatementType = 'INSERT'
BEGIN
INSERT INTO [dbo].Products (ProductName, SupplierID, CategoryID, QuantityPerUnit, UnitPrice, UnitsInStock, UnitsOnOrder, ReorderLevel, Discontinued)
VALUES (@ProductName, @SupplierID, @CategoryID, @QuantityPerUnit, @UnitPrice, @UnitsInStock, @UnitsOnOrder, @ReorderLevel, @Discontinued);
DECLARE @LastInserted INT;
SELECT @LastInserted = SELECT ScopeIdentity();
SELECT *
FROM [dbo].Products
WHERE ProductID = @LastInserted
END
IF @StatementType = 'UPDATE'
BEGIN
UPDATE Products
SET ProductName = @ProductName,
SupplierID = @SupplierID,
CategoryID = @CategoryID,
QuantityPerUnit = @QuantityPerUnit,
UnitPrice = @UnitPrice,
UnitsInStock = @UnitsInStock,
UnitsOnOrder = @UnitsOnOrder,
ReorderLevel = @ReorderLevel,
Discontinued = @Discontinued
WHERE ProductID = @ProductID;
SELECT *
FROM Products
WHERE ProductID = @ProductID
END
END
GO
但是,在执行脚本的那一刻,我得到了这个错误:
消息 156,级别 15,状态 1,服务器 e8535208dabe,过程 sp_MasterManagement,第 24 行
关键字“IF”附近的语法不正确。消息 156,级别 15,状态 1,服务器 e8535208dabe,过程 sp_MasterManagement,第 27 行
关键字“IF”附近的语法不正确。消息 156,级别 15,状态 1,服务器 e8535208dabe,过程 sp_MasterManagement,第 30 行
关键字“END”附近的语法不正确。
我不知道,也不明白为什么会出现此错误。到目前为止,我相信我的语法结构良好。有什么想法吗?
【问题讨论】:
-
试试这个
(SELECT Scope_Identity())而不是SELECT ScopeIdentity() -
旁注:您应该不为您的存储过程使用
sp_前缀。微软有reserved that prefix for its own use (see Naming Stored Procedures),你确实会在未来某个时候冒着名称冲突的风险。 It's also bad for your stored procedure performance。最好只是简单地避免sp_并使用其他东西作为前缀 - 或者根本不使用前缀!
标签: sql-server stored-procedures