Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to recognise that a constraint is unnamed in Sql Server?

Tags:

sql-server

Motivation - I want to fail our Gated Check-In whenever an unnamed constraint is added.

I could not find any dedicated designation for unnamed constraints in Sql Server. So, it is down to the pattern matching, which I can do in C#.

But what is the pattern? The simplest one that covers most of the cases is to check for "__", but it is not 100% reliable.

So, how would you check that a constraint is explicitly named given its name and having full access to the sys tables?

An alternative and even better solution would be if there is a way to disable unnamed constraints in the first place, but only for the current session.

like image 614
mark Avatar asked Nov 24 '17 13:11

mark


1 Answers

I could not find any dedicated designation for unnamed constraints in Sql Server

It is there. You can use the below

WITH T
     AS (SELECT is_system_named, name, type_desc
         FROM   sys.check_constraints
         UNION ALL
         SELECT is_system_named, name, type_desc
         FROM   sys.default_constraints
         UNION ALL
         SELECT is_system_named, name, type_desc
         FROM   sys.key_constraints
         UNION ALL
         SELECT is_system_named, name, type_desc
         FROM   sys.foreign_keys)
SELECT name,
       type_desc
FROM   T
WHERE  is_system_named = 'true' 
like image 169
Martin Smith Avatar answered Nov 15 '22 07:11

Martin Smith