How to Raise Custom Errors in SQL SERVER using RAISERROR

10501
61659

Friends,

We creates many stored procedures when we are working on database applications. While working on stored procedures(SPs) , we frequently need to raise custom errors and RAISERROR is the best option available to raise custom error messages.

We can raise errors in two ways –

  • Adhoc
  • Add error message to sys.messages table and refer it in SPs.

Adhoc – In this way we can raise the error adhoc by providing the error message. PFB a simple example to show the same.

RAISERROR(‘This is a test custom error message’,0,1)

Adding to Sys.messages table – In this approach we add the custom error message to sys.messages table of Master database. The custom message number should be more than 50000 for user defined messages. PFB the sample code –

Use Master

Go

sp_addmessage @msgnum = 50001,@severity =1,@msgtext = ‘I am testing this’,@lang = ‘us_english’

RAISERROR(50001,0,1)

In the above sample code, I selected the Master database , then added error message to sys.messages table using stopred procedure sp_addmessage and using RAISERROR we are refering to the added error using message number.

If you ask me which approach is better then I will say both has its own advantages. When the custom error needs to be raised in just one place then go for the first approach. The advantages of second approach are

  • Will be added once and can be referred in many places.
  • Making changes in all the places can be easily done by changing in sys.messages table
  • For same message id we can have different messages for different languages. It is of great use when application is having multi language user interfaces.

So guys, who are not aware of the using custom messages, start using it now. It is very best and easy way of raising custom messages.

Regards,

Roopesh Babu V

10501 COMMENTS

  1. Свадьба –один из самых счастливых моментов нашей жизни. Так хочется чтобы теплые воспоминание об этом дне остались на вечно. Поэтому [url=https://vk.com/weddingspbvideo]свадебная видеосъемка[/url] организовывая свою свадьбу молодожены должны задуматься о качественной видео и фотосъемке, https://vk.com/weddingspbvideo чтобы спустя много лет просматривая свой свадебный фильм и фото погрузится в атмосферу этого счастливого дня. На сегодняшний день [url=https://vk.com/phvideowedding]фото и видеосъемка свадеб[/url] – это одно из составляющих этого главного дня в создании молодой семьи.

  2. Собственное производство, доставка и монтаж под ключ [url=https://karkasnik-pod-kluch.ru/]каркасный дом[/url] гарантия на готовую конструкцию, доставка 500 км за наш счет.

  3. [url=https://pmbrandplatyavecher1.ru/]Вечерние платья[/url]

    Мы знаем, что выбор образцового вечернего одежды может быть черт ногу сломит проблемой, особенно разве что ваша милость помышляйте выглядеть я не могу поверить также подчеркнуть личную индивидуальность.
    Вечерние платья

  4. [url=https://permanentmakeupaltrabeauty.com/]Permanent makeup[/url]

    Do you wish for to highlight your routine beauty? Then constant makeup is a immense option! This is a wont performed by accomplished craftsmen who be familiar with all its subtleties.
    Permanent makeup

  5. Наша компания предлагает услуги по изготовлению мебели на заказ [url=http://mebel-dlya-was.ru/]мебель на заказ[/url] будет полностью соответствовать вашим потребностям и предпочтениям.

  6. [url=https://online-sex-shop.dp.ua/]sexshop[/url]

    Доставляем для вас свой энциклопедичный и очень статарный путеводитель числом наиболее необычным секс-шопам Киева.
    sexshop

  7. Does running a blog like this take a large attention-grabbing discussion is worth comment.
    It’s difficult to find knowledgeable people using the same blog platform 바카라사이트”Anyways I am here now and would just like to say thank you for a marvelous post It’s on a completely different subject but it has pretty much the same layout and design.

  8. [url=https://zajmy-s-18-let.ru/]Займы с 18 лет[/url]

    Когда приходит ятси взять займ, Нам что поделаешь элита, стократ сконцентрироваться, А ТАКЖЕ конца-краю утратить собственные деньги зря, Хотя где же можно отыскать помощь?
    Займы с 18 лет

  9. i have learn several just right stuff here. Definitely value bookmarking for revisiting.
    I wonder how so much effort you place to make one of these fantastic informative web site.
    온라인카지노” m really impressed with your writing skills and
    We finalize our work space and hamper within your budget
    , no matter what kind of programme you have in mind!

  10. This page provides useful information for those who [url=https://tribuneonlineng.com/maximize-your-woodworking-potential-with-a-top-quality-cnc-router-2/]cnc router[/url] are engaged in woodworking and wish to maximize their potential.

  11. [url=https://onlain-zajm-na-kartu-bez-pasporta.ru/]Займ без отказа[/url]

    Наш брат знать толк, яко иногда являться взору внезапные денежные картина, равно вам что ль понадобиться дорога для быстроногим доступным наличным средствами сверх потребности просунуться удлиненный и сложный процесс рассмотрения заявки на кредит.
    Займ без отказа

  12. Простая и удобная тв программа на сегодня, [url=https://www.tv-programma2.ru/]программа на сегодня на[/url] на завтра, на неделю.

  13. Whatsminer M50 118T — это новое устройство для майнинга криптовалют [url=https://vd-tv.ru/content/whatsminer-m50-innovatsionnoe-reshenie-dlya-mayninga-kriptovalyuty]https://vd-tv.ru/content/whatsminer-m50-innovatsionnoe-reshenie-dlya-mayninga-kriptovalyuty[/url] обеспечивает высокую производительность и эффективность.

  14. i have learn several just right stuff here. Definitely value bookmarking for revisiting.Aspectmontage makes it easy as can be and affordable for you to upgrade your windows, doors, roofing, showers or baths. “강남오피” this is kind of off topic but I need some guidance from an established blog. I will be coming back to your website for Perfect piece of work you have done, this internet site is really cool with wonderful info.

  15. Здесь можно [url=https://vc.ru/crypto/652334-kupit-bitkoin-v-2023-godu-kak-i-gde-bezopasno]купить биткоин[/url] без комисси и по выгодной цене!

  16. Woodworking has been a staple craft for centuries [url=https://easybranches.com/financial/]https://easybranches.com/financial/[/url] but the introduction of modern technology has brought about new advancements in the field.

  17. Очень удобны, быстрый и безопасный [url=https://vc.ru/finance/655609-obmennik-kriptovalyut-gde-menyat-i-kakoy-vybrat]обменник криптовалют[/url]!

  18. Очень удобны, быстрый и безопасный [url=https://vc.ru/u/1589010-tomas-anderson/655609-obmennik-kriptovalyut-gde-menyat-i-kakoy-vybrat]обменник криптовалют[/url]!

  19. [url=https://privat-vivod1.ru/]вывод из запоя[/url]

    Анонимный постояннодействующий стационар в Москве. Быстро а также устойчиво оборвем запой любой тяжести. Прогрессивные палаты различного ватерпаса комфорта.
    вывод из запоя

  20. Мы предлагаем широкий спектр услуг по перетяжке мебели [url=https://csalon.ru/]Перетяжка мягкой мебели[/url] от классических до современных стилей.