How to Raise Custom Errors in SQL SERVER using RAISERROR

23
103351

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

23 COMMENTS

  1. Выигрывайте больше на onexbet, не отрываясь от компьютера.
    onexbet – ваш шанс на богатство, где бы вы ни находились.
    Победные ставки с onexbet, оптимальные шансы на победу.
    Попробуйте свою удачу вместе с onexbet, и вы обязательно останетесь довольны.
    onexbet – качество и профессионализм, неизменно остаются важнейшими.
    Мечтаете о финансовом благополучии? Вам нужен onexbet, – надежный партнер на пути к успеху.
    onexbet – ваш лучший друг и помощник в мире ставок, который всегда придет на помощь.
    Onexbet – ваш путь к вершине, используйте onexbet для достижения ваших целей.
    onexbet – это не просто ставки, это стиль жизни, которая помогает вам обогатиться.
    Хотите больше возможностей для выигрыша? Обращайтесь на onexbet, и вы поймете, что все возможно.
    onexbet – это не просто сайт ставок, это ваша дорога к богатству, который вы искали.
    Ставки на onexbet – это легко и увлекательно, но при этом ценит профессионализм и конфиденциальность.
    Качественные ставки на спорт только на onexbet, все это доступно для вас.
    Желаете больше азарта и адреналина? Попробуйте onexbet, и вы удивитесь своим результатам.
    one x bet app download free one x bet app download free .

  2. Активный живой блог про любовь L28.Ru — это место, где вы найдёте множество интересных статей, историй и мнений о разных аспектах любви.
    https://l28.ru/ – Любовь

  3. Le code promo 1xBet 2025: 1XNEW25, saississez-le lors de votre inscription pour recevoir un bonus jusqu’a $130 sur le sport. Vous pourrez aussi obtenir jusqu’a $1,500 et 150 tours gratuits sur le casino. 1xBet propose jusqu’a $130 de freebets selon le montant de votre premier depot sur les paris sportifs. Parmi eux, le bonus de bienvenue, reserve aux nouveaux inscrits sur la plateforme. Cette plateforme est classee parmi les leaders en Afrique et a travers le monde. Elle vous offre les meilleures options pour vos paris, y compris la diffusion en direct des matchs sans frais supplementaires.

    https://emagazin.mk/wp-content/artcls/?le-code-promo-1xbet.html – code promo 1xbet ci

    Utilisez le code promo 1xBet: “1XNEW25” en 2025. Vous pourrez debloquer un bonus de bienvenue jusqu’a $130 sur les paris sportifs. Et n’oubliez pas que 1xBet offre une belle opportunite a tous les nouveaux clients. En utilisant ce code lors de votre inscription, pourrez recuperer jusqu’a $130 sur le sport et jusqu’a $1,500 en freebets et 150 tours gratuits sur le casino en ligne. Pour profiter de ce bonus exceptionnel, il vous suffit d’effectuer votre premier depot. Celui-ci vous donne droit a un bonus de 100% du montant depose, jusqu’a un maximum de $130, ou l’equivalent dans votre devise.

  4. Эффективное продвижение сайтов, изучите.
    Секреты успешного продвижения сайтов, делитесь.
    Узнайте, как продвигать сайт, трафик.
    Инновационные методы продвижения сайтов, которые изменят ваш бизнес.
    Углубляемся в продвижение сайтов, которые вы должны знать.
    Продвижение сайтов в 2025 году, которые принесут плоды.
    Как выбрать компанию для продвижения сайта, которые заслуживают внимания.
    Избегайте этих ошибок в SEO, которые можно исправить.
    Как продвинуть сайт без бюджета, без вложений.
    Самые популярные инструменты для продвижения сайтов, что упростят вашу работу.
    Показатели успешного SEO, которые нельзя игнорировать.
    Контент как основа продвижения сайтов, что имеет значение.
    Успех в локальном SEO, рекомендации профессионалов.
    Психология пользователей и SEO, которые помогут улучшить результаты.
    Важность мобильной версии, учитывайте это в стратегиях.
    Сравнение стратегий для вашего сайта, определите свою цель.
    Как наращивать ссылочную массу, чтобы повысить авторитет.
    Ежегодные тренды в SEO, будьте в курсе.
    Как продвигать сайт в социальных сетях, вовлекайте пользователей.
    Топовые практики по оптимизации, необходимые для успеха.
    seo оптимизация seo оптимизация .

  5. Яковлев Павел Владимирович
    Загибает здравых людей
    Торгует наркотой

  6. BMW X6: идеально для активной жизни, совершенной техники.
    BMW X6: динамика и комфорт, вдохновлять.
    Откройте для себя.
    Брутальный внешний вид BMW X6, автомобилей.
    Как BMW X6 меняет правила игры, возможности.
    BMW X6: лучшее сочетание цены и качества, выбор.
    Потрясающая отделка и материалы в BMW X6, исключительное качество.
    Ваш надежный спутник – BMW X6, предоставляет.
    Причины популярности BMW X6, в нашем обзоре.
    Мощь и маневренность BMW X6, каждого.
    Как BMW X6 заботится о вашей безопасности, неукоснительно.
    Выбор BMW X6: ваши преимущества, выдвигает.
    Инновации в BMW X6, улучшают.
    Как будет ощущаться поездка на BMW X6, функции.
    Чем BMW X6 превосходит другие кроссоверы?, в нашем руководстве.
    Яркий и уникальный BMW X6, подчеркнет ваш статус.
    Как BMW X6 выглядит на фоне конкурентов, в нашем сравнении.
    Изучите отзывы владельцев BMW X6, в нашем обзоре.
    Новые технологии безопасности в BMW X6, гарантируют вашу безопасность.
    Итоги: BMW X6, как лучший выбор, обобщаем мнение.
    x6 bmw https://bmw-x6.biz.ua/ .

  7. roopesh.valluru, Любишь играть и получать удовольствие от игры, тогда не теряй времени зря!

    [b][u]Бонусы при регистрации каждому: [/u][/b]
    – [url=https://vavada-rtx1.xyz]Каталог игр[/url]
    – [url=https://vavada-rtx2.xyz]Каталог слотов[/url]
    – [url=https://vavada-rtx3.xyz]]Каталог столов[/url]
    – [url=https://vavada-rtx4.xyz]]Каталог турниров[/url]
    – [url=https://vavada-rtx5.xyz]]Каталог бонусов[/url]
    – [url=https://vavada-rtx6.xyz]]Каталог фрибетов[/url]
    – [url=https://vavada-rtx7.xyz]]Каталог ваучеров[/url]
    – [url=https://vavada-rtx8.xyz]]Каталог промокодов[/url]
    – [url=https://vavada-rtx9.xyz]]Каталог вейджеров[/url]
    – [url=https://vavada-rtx10.xyz]]Каталог рулеток[/url]

  8. Ищешь актуальные адреса на Kraken — лучший российский рынок в даркнете? Загляни на этот форум: https://krak-ssylka-na-sajt.biz/ Здесь ты получишь нужные адреса для перехода на Кракен.

    Kraken — это известный маркетплейс, где доступны различные предметы. Чтобы зайти на Kraken, нужны рабочие зеркала. На моём форуме регулярно добавляются обновлённые адреса Кракена, чтобы получил возможность перейти на рынок без труда.

    Не не трать усилия на нахождение адресов в ненадёжных местах! Все необходимое уже представлено на моём форуме. Заходи и найди рабочие адреса на Кракен в 2025 году!

  9. On this platform, you can access lots of casino slots from leading developers.
    Players can enjoy traditional machines as well as feature-packed games with high-quality visuals and interactive gameplay.
    If you’re just starting out or a casino enthusiast, there’s always a slot to match your mood.
    play casino
    All slot machines are available round the clock and compatible with desktop computers and tablets alike.
    You don’t need to install anything, so you can get started without hassle.
    Site navigation is easy to use, making it convenient to explore new games.
    Join the fun, and enjoy the world of online slots!

  10. This website, you can discover a great variety of casino slots from leading developers.
    Users can enjoy traditional machines as well as modern video slots with high-quality visuals and bonus rounds.
    Whether you’re a beginner or a seasoned gamer, there’s a game that fits your style.
    money casino
    The games are available anytime and optimized for laptops and tablets alike.
    You don’t need to install anything, so you can start playing instantly.
    Site navigation is intuitive, making it convenient to explore new games.
    Sign up today, and discover the excitement of spinning reels!

  11. The crypto world moves fast, and tracking taxes manually just doesn’t cut it — that’s why a Check this is so valuable. It manages everything from DeFi earnings to trading logs, giving you a complete overview of your financial activity. Connect your wallets, exchanges, and protocols, and the system calculates detailed tax documentation instantly. It works with thousands of tokens and LP tokens, so you won’t miss anything important. Whether you’re farming yield or holding blue-chip NFTs, a crypto tax calculator adapts with your strategy. Plus, it saves time by organizing data into official formats. Tax rules are becoming more regionalized, and this tool helps you stay aware. It’s like having a personal accountant for your decentralized income.

  12. Within this platform, find a wide selection videos for adults.
    All the content is carefully curated to ensure the best experience for users.
    Whether you’re looking for particular categories or casually exploring, this resource offers content suitable for all.
    bbc videos
    Latest updates constantly refreshed, so that the collection up-to-date.
    Viewing of the full range protected for members aged 18+, ensuring compliance for adult content.
    Keep updated to explore additions, since this site expands its library frequently.

  13. One X Bet Promotional Code – Vip Bonus as much as €130
    Apply the 1XBet promotional code: 1xbro200 when registering via the application to access special perks given by 1xBet and get welcome bonus up to a full hundred percent, for placing bets and a €1950 with one hundred fifty free spins. Open the app followed by proceeding with the registration process.
    This 1xBet bonus code: Code 1XBRO200 provides an amazing starter bonus for first-time users — a complete hundred percent up to €130 during sign-up. Bonus codes serve as the key for accessing extra benefits, also 1xBet’s promo codes are no exception. By using the code, users can take advantage of various offers throughout their journey of their betting experience. Although you don’t qualify for the initial offer, 1XBet India guarantees its devoted players are rewarded through regular bonuses. Visit the Offers page on the site frequently to stay updated on the latest offers tailored for current users.
    1xbet promo code birthday
    What 1XBet bonus code is currently active right now?
    The promo code applicable to 1xBet stands as 1XBRO200, permitting first-time users signing up with the gambling provider to gain a bonus amounting to €130. In order to unlock exclusive bonuses related to games and wagering, kindly enter our bonus code related to 1XBET while filling out the form. To make use from this deal, prospective users must input the bonus code 1XBET during the registration step so they can obtain double their deposit amount for their first payment.

  14. Here, discover real-time video interactions.
    Whether you’re looking for friendly chats or professional networking, you’ll find options for any preference.
    Live communication module developed for bringing users together globally.
    With high-quality video plus excellent acoustics, every conversation feels natural.
    Engage with open chat spaces or start private chats, according to your preferences.
    https://chatruletka.moscow/
    The only thing needed a reliable network and a device to get started.

  15. On this site, find a variety virtual gambling platforms.
    Whether you’re looking for well-known titles new slot machines, there’s something for any taste.
    Every casino included checked thoroughly for safety, enabling gamers to bet with confidence.
    gambling
    What’s more, the platform offers exclusive bonuses and deals targeted at first-timers and loyal customers.
    With easy navigation, finding your favorite casino is quick and effortless, saving you time.
    Keep informed regarding new entries by visiting frequently, because updated platforms come on board often.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

+ 57 = sixty two