Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Use the following if you do not wish to use a trial and error method: </p> <pre><code>DECLARE @schema NVARCHAR(20) DECLARE @table NVARCHAR(50) DECLARE @column NVARCHAR(50) DECLARE @SQL NVARCHAR(1000) DECLARE @ID INT DECLARE @exists INT DECLARE @x NVARCHAR(100) SELECT @x = '@exists int output', @ID = 1, @schema = 'dbo', @table = 'Gebruiker', @column = 'GebruikerHasGebruiker_id' SELECT @SQL = 'SELECT @exists = 1 WHERE EXISTS( ' + STUFF(( SELECT ' UNION ALL SELECT ' + U2.COLUMN_NAME + ' AS ID FROM ' + U2.TABLE_SCHEMA + '.' + U2.TABLE_NAME + ' WHERE ' + U2.COLUMN_NAME + ' = ' + cast(@id as VARCHAR(10)) FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS R INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE U ON R.UNIQUE_CONSTRAINT_NAME = U.CONSTRAINT_NAME INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE U2 ON R.CONSTRAINT_NAME = U2.CONSTRAINT_NAME WHERE U.TABLE_SCHEMA = @schema AND U.TABLE_NAME = @table AND U.COLUMN_NAME = @column FOR XML PATH('') ),1,11, '') + ')' EXEC sp_executesql @SQL, @x, @exists = @exists OUTPUT IF 1 &lt;&gt; @exists BEGIN -- do you stuff here END </code></pre> <p>But in 99% of the cases you could do this, it's overkill. It is faster if you already know the FKs and just create a query. </p> <p>Edit: A little explanation. This dynamic SQL looks in the INFORMATION SCHEMA to see all relations with other tables. It uses that information to create a query to check if your ID exists in that table. With a UNION it adds all results and returns 1 if any results are found. This can be used for any database, for any column, as long as you don't check for a FK over multiple columns. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload