Create custom error message in check constraints in SQL SERVER 2008 - sql-server

I'd like to see the ability to attach custom error messages to CONSTRAINT objects, specifically CHECK constrints. Either directly or via a custom error number in sysmessages.
I've seen developers have to create triggers. I think that's not a good reason to implementing it.
I'm using SQL SERVER 2008.

You could name your constraint with a user message.
For Example:
ADD CONSTRAINT
[Foo cannot be greater than Bar. Please be sure to check your foos and bars next time.]
CHECK (foo <= Bar)

I know this is an old post, but I've found something that may make it a bit easier to provide clearer error messages for check constraints to the end-user: the names of check constraints can include carriage returns and line feeds, so the error message can be made a bit easier to see.
E.g. creating the following constraint produces the error message below. (the blank lines between the [ and ] are intentional i.e. they are part of the constraint name.)
ALTER TABLE dbo.Sales WITH CHECK ADD CONSTRAINT [
ERROR:
You have stupidly entered a negative selling price. Please report to detention.
] CHECK ([SellingPrice] >= 0.00)
GO
And when this constraint fails, the resulting message is:
I tried putting markup in the error message (i.e. constraint name), like <b>message</b> and *message*, but to no avail. And it may be possible, but really unwieldy, to use this for foreign key constraints as well. I haven't tried it.
So it's not a 100% solution, but hopefully easier for the user to see the intended error message.
Edit (2022-02-09): Since database object names are stored using the sysname data type (search for 'sysname' on this page), they cannot be longer than 128 characters. Use short error messages 😄

You can't directly
A CHECK constraint fails with a standard error message. You could use a TRY/CATCH block to parse the error and throw your own (RAISERROR) or use a trigger.
I'd check first so it doesn't fire, either is SQL or in client code. And of course you leave the constraint there to protect data integrity
So if you have a constraint
ALTER TABLE MyTable WITH CHECK
ADD CONSTRAINT CK_MyTable_foobar CHECK (#foo <= #Bar)
You run the following SQL code or equivalent in your client code:
...
IF #foo > #bar
RAISERROR ('foo (%i) can not be greater than bar (%i)', 16, 1, #foo, #bar)
INSERT MyTable (foo, bar) VALUES (#foo, #bar)
....

Related

linked server: four prefixes work with select but not alter

I have an SQL Server 13.0 box with
[EC2AMAZ\SQLEXPRESS] as a linked server
I'm running the following commands on the SQL Server 13.0 box
and this select statements work just fine:
select * from [EC2AMAZ\SQLEXPRESS].[import].[dbo].[table]
but this:
ALTER TABLE [EC2AMAZ\SQLEXPRESS].[import].[dbo].[table] ADD field
nvarchar(4000)
throws the error:
The object name 'EC2AMAZ\SQLEXPRESS.import.dbo.table' contains more than the maximum number of prefixes. The maximum is 2.
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near 'field'.
why is it okay to use four prefixes for select but not alter?
You can't run DDL against a linked server. One workaround is to use dynamic SQL:
EXEC [EC2AMAZ\SQLEXPRESS].[import].sys.sp_executesql
N'ALTER TABLE [dbo].[table] ADD field nvarchar(4000);';
The syntax diagram in the official documentation does not include four-part names for ALTER TABLE:
It is officially documented (albeit indirectly) for SELECT in the docs for FROM {<table_source>}:
If the table or view exists outside the instance of SQL Serverl, use a four-part name in the form linked_server.catalog.schema.object.
(Typo is free!)
Such reference does not exist for ALTER TABLE. Yes, it kind of sucks that we have to infer from lack of documentation that something isn't possible, but imagine even trying to document all of the things a feature can't do?
This car:- cannot be used as a flotation device- is not a sufficient source of vitamin C- cannot vote- may not respond to "Betsy"- does not fly- will not fit into bell-bottoms- can't run on carrot juice, diet pepsi, or metamucil...
There is probably a long list of why, including the types of locks required to make schema modifications. But I suspect why isn't the thing that's important here, because answering that question isn't going to change the problem or help you avoid needing to use a workaround.

Could not create foreign key constraint. There are 'NIF' values of entity x (new table) with no corresponding value in entity y

I'm struggling a bit to overcome this obstacle that is to create a table with a foreign key to another table. It looks simple right? It is, but unfortunately i'm not being successfull. The error thrown is the one in the title. Has anyone else had this error before? How did you resolved it? I'm using SQL Server 2014 but the error is thrown through Outsystems IDE.
Best regards,
Rafael Valente
It would help if you could post a picture of your datamodel for us to take a look.
One way of dealing with this kind of errors in OutSystems is inspecting the database itself. There's a system table called ossys_espace. Get your espace id from there. Then query ossys_entity to see which is the physical table name for that entity and check if there's something wrong with it.
There's also the possibility that you've created a table in the past that is causing the error. Check for the entities with the flag deleted set to true in that table. If it helps, there's this Forge component that you can you to clean those deleted entities.
If you have access to the server you can also look at the generated SQL and understand if there's a problem with it.
I find that error weird, but you might be bumping into a bug, and for sure we want to know that :)

Getting Valid Inputs for Constrained Field

I have an Informix database that I really would have liked an 'enum' field for. Being that Informix (At least in the version I am constrained to) has no built-in enum type I used some Google-Foo to find out that I could constrain a VARCHAR field to only allow certain values like so:
ALTER TABLE table ADD CONSTRAINT CHECK (type IN ('type1', 'type2', 'type3'));
This seems to work well. Now I need to connect to the database from a Perl script that checks user input against those valid values. I can of course check them in code and make sure my code knows what the values are that the database requires, but I wondered if there is any way I could have my script query the constraint on the database therefore if I need to Add/Remove a valid input at a later time I could just alter the constraint and the processing code would adapt.
Any suggestions would be greatly appreciated.
If you encapsulate you database access in a DBIx::Class schema, you gain this kind of validation "as a bonus".
A simple way of generating the schema from a pre-existing database is by
dbicdump.

Is it possible to define error message for UNIQUE KEY constraint in SQL SERVER when it is called by EF 4.0?

I don't need to execute duplicatation query like checking some column is unique or not because this operation always execute with SQL Server constraint. However, default error message from SQL Server is not well-defined for end-user.
Do you have any idea for change/redefine error message to be more user-friendly?
PS. I execute all query via Entity Framework 4.0.
The only way I know to do this is to catch SqlException and then check the Number property. This property is a short-cut to the first Error in the Errors property, and if you are worried about the possiblity of multiple error conditions, you could use that instead.
Once you know the sql error number, you can provide a more user-friendly message. Unfortunately, I do not know of a way to get a nice list of common sql server error numbers, besides doing select * from sys.messages, but it can be a little overwhelming to search through them.
I only cared about a few specific error numbers and created the error conditions manually to determine the numbers:
547 foreign key conflict
2601 unique index violation
2627 primary key violation
On any other error number, I just provide a generic message indicating that there was a problem with the database. In all cases, I log the exception information for later use (using NLog).

Can anyone explain how this constraint functions?

Can anyone explain how this constraint functions and how its affects insertion of records into this table? Running win sql 2k5. Having issue with trying to insert data.
ALTER TABLE [dbo].[ws_shiptable] ADD CONSTRAINT [DF_ws_shiptable_ps_processed] DEFAULT (0) FOR [ps_processed]
It adds a default value of 0 for column ps_processed. If you do an insert and you don't specify a value for ps_processed, it'll default to 0. What is the issue you are having? Do you get error messages you can post? A default value shouldn't give you trouble, but make sure ps_processed has the right data type. I suspect it'll be a bit field?
If no value is provided for the column ps_processed then SQL Server will set the value to zero

Resources