Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make sure a string column has no spaces?

I have currently a primary key field of nvarchar(50), I am willing to change the type, if I can get it to accept no white space. Is there anyway to do this?

Should allow the following:

------
AAAA
BBBB
CCCC

Should not allow the following:

------
AA AAA
BBBB B
C CCCC
like image 913
Bill Software Engineer Avatar asked May 22 '12 18:05

Bill Software Engineer


People also ask

How do I remove blank spaces in SQL column?

SQL Server TRIM() Function The TRIM() function removes the space character OR other specified characters from the start or end of a string. By default, the TRIM() function removes leading and trailing spaces from a string. Note: Also look at the LTRIM() and RTRIM() functions.

Should column names have spaces?

Column names can contain any valid characters (for example, spaces).

How do you query column names with spaces?

To select a column name with spaces, use the back tick symbol with column name. The symbol is ( ` `). Back tick is displayed in the keyboard below the tilde operator ( ~).

Can column name contain space?

Blanks spaces are restricted in the naming convention of the database object's name and column name of the table. If you want to include the blanks space in the object name or column name, the query and application code must be written differently.


1 Answers

You could add the following check constraint:

CHECK LEN(col) = LEN(REPLACE(col, ' ', ''));

...or...

CHECK (col NOT LIKE '% %');

...or...

CHECK (CHARINDEX(' ', col) = 0)

Example:

USE tempdb;
GO

CREATE TABLE dbo.bar(foo NVARCHAR(50) PRIMARY KEY);

ALTER TABLE dbo.bar ADD CONSTRAINT chkNoSpaces
 CHECK (foo NOT LIKE '% %');

Succeeds:

INSERT dbo.bar(foo) SELECT 'AAAA';
GO

Fails:

INSERT dbo.bar(foo) SELECT 'AA AA';
GO

Results:

Msg 547, Level 16, State 0, Line 1
The INSERT statement conflicted with the CHECK constraint "chkNoSpaces". The conflict occurred in database "tempdb", table "dbo.bar", column 'foo'.
The statement has been terminated.

Clean up:

DROP TABLE dbo.bar;

EDIT

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):

  1. In Object Explorer, right-click your table and select Design
  2. Right-click your column in the upper grid and select Check Constraints...
  3. Click Add
  4. Type column_name NOT LIKE '% %' in the "Expression" box (use your actual column name, not column_name)
  5. If you think you already have data that violates the constraint, change the option for "Check Existing Data..." to No (and promptly go fix that data)
  6. Click Close
  7. Click on the "Save" icon on the toolbar

Note that the UI actually changes the construction of the clause, e.g. (NOT col_name LIKE '% %')

like image 178
Aaron Bertrand Avatar answered Sep 21 '22 17:09

Aaron Bertrand