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
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.
Column names can contain any valid characters (for example, 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 ( ~).
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.
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):
column_name NOT LIKE '% %'
in the "Expression" box (use your actual column name, not column_name
)Note that the UI actually changes the construction of the clause, e.g. (NOT col_name LIKE '% %')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With