Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You could add the following check constraint:</p> <p><strike><code>CHECK LEN(col) = LEN(REPLACE(col, ' ', ''));</code></strike></p> <p>...or...</p> <pre><code>CHECK (col NOT LIKE '% %'); </code></pre> <p>...or...</p> <pre><code>CHECK (CHARINDEX(' ', col) = 0) </code></pre> <p>Example:</p> <pre><code>USE tempdb; GO CREATE TABLE dbo.bar(foo NVARCHAR(50) PRIMARY KEY); ALTER TABLE dbo.bar ADD CONSTRAINT chkNoSpaces CHECK (foo NOT LIKE '% %'); </code></pre> <p>Succeeds:</p> <pre><code>INSERT dbo.bar(foo) SELECT 'AAAA'; GO </code></pre> <p>Fails:</p> <pre><code>INSERT dbo.bar(foo) SELECT 'AA AA'; GO </code></pre> <p>Results:</p> <blockquote> <p>Msg 547, Level 16, State 0, Line 1 <br>The INSERT statement conflicted with the CHECK constraint "chkNoSpaces". The conflict occurred in database "tempdb", table "dbo.bar", column 'foo'. <br>The statement has been terminated.</p> </blockquote> <p>Clean up:</p> <pre><code>DROP TABLE dbo.bar; </code></pre> <p><strong>EDIT</strong></p> <p>If you need to do this through the UI for some reason (again I recommend you do this with a script that you can make atomic, repeatable, save to a file, store in source control, etc):</p> <ol> <li>In Object Explorer, right-click your table and select <kbd>Design</kbd></li> <li>Right-click your column in the upper grid and select <kbd>Check Constraints...</kbd></li> <li>Click <kbd>Add</kbd></li> <li>Type <code>column_name NOT LIKE '% %'</code> in the "Expression" box (use your actual column name, not <code>column_name</code>)</li> <li>If you think you already have data that violates the constraint, change the option for "Check Existing Data..." to <kbd>No</kbd> (and promptly go fix that data)</li> <li>Click <kbd>Close</kbd></li> <li>Click on the "Save" icon on the toolbar</li> </ol> <p>Note that the UI actually changes the construction of the clause, e.g. <code>(NOT col_name LIKE '% %')</code></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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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