MulaiMulai sekarang secara gratis

FORMATMESSAGE with message string

Every time you sell a bike in your store, you need to check if there is enough stock. You prepare a script to check it and throw an error if there is not enough stock.

Latihan ini adalah bagian dari kursus

Transactions and Error Handling in SQL Server

Lihat Kursus

Petunjuk latihan

  • Set @sold_bikes to a value greater than @current_stock (e.g. 100).
  • Customize the error using FORMATMESSAGE with the text 'There are not enough %s bikes. You have %d in stock.' as the first parameter, @product_name as the second parameter, and @current_stock as the third parameter.
  • Pass to the THROW statement the @my_message variable and click Run Code (not Run Solution). You will see the error.
  • Set @sold_bikes in DECLARE statement back to 10. Run the code without errors.

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

DECLARE @product_name AS NVARCHAR(50) = 'Trek CrossRip+ - 2018';
-- Set the number of sold bikes
DECLARE @sold_bikes AS INT = ___;
DECLARE @current_stock INT;

SELECT @current_stock = stock FROM products WHERE product_name = @product_name;

DECLARE @my_message NVARCHAR(500) =
	-- Customize the error message
	FORMATMESSAGE(___, ___, ___);

IF (@current_stock - @sold_bikes < 0)
	-- Throw the error
	THROW 50000, ___, 1;
Edit dan Jalankan Kode