CREATE PROCEDURE sp_product_listing
(
@product varchar(30),
@month datetime,
@year datetime
)
AS
SELECT
'product_name' = products.name,
products.unit_price,
products.quantity_in_stock,
'supplier_name' = suppliers.name
FROM
suppliers
INNER JOIN
products ON suppliers.supplier_id = products.supplier_id
INNER JOIN
order_details ON products.product_id = order_details.product_id
INNER JOIN
orders ON order_details.order_id = orders.order_id
WHERE
products.name = @product
AND MONTH ('orders.order_date') = @month
AND YEAR ('orders.order_date') = @year;
GO
当有些人尝试使用错误的输入执行过程时,而不是在异常块中获取此错误消息
Msg 8114, Level 16, State 5, Procedure sp_product_listing, Line 0
Error converting data type varchar to datetime.
答案 0 :(得分:0)
从我的评论中:不可能在同一个sp内验证SP的输入参数!
您需要对输入的婴儿车进行验证。 所以听到这是一个使用错误处理方法执行此操作的简单示例。
GO
CREATE PROCEDURE ERROR_TEST
(
@month DATETIME,
@year DATETIME
)
AS
BEGIN
SELECT
MONTH (@month) [month],
YEAR (@year) [year]
END
GO
现在使用相同的输入参数创建一个类似的sp。
GO
CREATE PROCEDURE ERROR_TEST_1
(
@month_1 VARCHAR(50),
@year_1 VARCHAR(50)
)
AS
BEGIN TRY
EXEC ERROR_TEST @month_1,@year_1
END TRY
BEGIN CATCH
IF ERROR_NUMBER() = 8114 --> update asper your error OR set > 0
BEGIN
PRINT 'INVALID MONTH OR YEAR'
END
END CATCH;
GO
示例执行:
EXEC ERROR_TEST_1' 1',' 2 ' --->错误结果
EXEC ERROR_TEST_1&#39; 2015-11-15 &#39;,&#39; 2015-11-15 &#39; < /强> ---&GT;正确的结果