SQL CHECK CONSTRAINT VARCHAR - sql

create table table1
(
column1 varchar2(8)
check constraint column1_ch check ........
);
How do I do a check for a data that the first 4 char is a specific set of alphabets while the last 4 is numbers? and as well as a range of values.
examples, data can be ABCD2121, ABCD1111.
range - ABCD0001 to ABCD9999
So 'ABCD' is fixed while the numbers are changing.
I've foudn online about using '[]" to define the numbers but i'm not able to integrate it into my constraint.
Thanks

The easiest way is to do this using a regular expression:
alter table table1
add constraint chck_code check (regexp_like(column1, '(ABCD)[0-9]{4}') );

If you've got a fixed set of prefixes, use regexp_like and enumerate the prefix list:
alter table test_1
add constraint chk_col1 check(regexp_like(column1, '(ABCD|EFGH)[0-9]{4}'));
This will allow ABCD and EFGH as prefixes, followed by exactly 4 digits.

Your check condition should be as follows:
(column1 LIKE 'ABCD[0-9][0-9][0-9][1-9]')
Edit: Modified to use a set prefix vs. a range for the alpha characters.
Here's a solution using Microsoft SQL Server that illistrates this:
DECLARE #MyTable TABLE
(column1 varchar(8) check (column1 LIKE 'ABCD[0-9][0-9][0-9][1-9]'))
INSERT INTO #MyTable (column1)
SELECT 'ABCD0000'
UNION SELECT 'ABCD2121'
UNION SELECT 'ABCD1111';
SELECT *
FROM #MyTable;
INSERT INTO #MyTable (column1)
SELECT 'ABCD000A'; --<== Fails!
INSERT INTO #MyTable (column1)
SELECT 'ABCD221'; --<== Fails!

Related

How to convert or cast int to string in SQL Server

Looking at a column that holds last 4 of someone's SSN and the column was originally created as an int datatype. Now SSN that begin with 0 get registered as 0 on the database.
How can I convert the column and it's information from an int into a string for future proof?
You should convert. CONVERT(VARCHAR(4), your_col)
If you specifically want zero-padded numbers, then the simplest solution is format():
select format(123, '0000')
If you want to fix the table, then do:
alter table t alter column ssn4 char(4); -- there are always four digits
Then update the value to get the leading zeros:
update t
ssn4 = format(convert(int, ssn4), '0000');
Or, if you just want downstream users to have the string, you can use a computed column:
alter table t
add ssn4_str as (format(ssn4, '0000'));
If you want to add leading zeros, use:
SELECT RIGHT('0000'+ISNULL(SSN,''),4)
First thing never store SSN or Zip Code as any numeric type.
Second you should fix the underlying table structure not rely on a conversion...but if you're in a jam this is an example of a case statement that will help you.
IF OBJECT_ID('tempdb..#t') IS NOT NULL
BEGIN
DROP TABLE #t
END
GO
CREATE TABLE #t(
LastFourSSN INT
)
INSERT INTO #t(LastFourSSN)
VALUES('0123'),('1234')
SELECT LastFourSSN --strips leading zero
FROM #t
SELECT -- adds leading zero to anything less than four charaters
CASE
WHEN LEN(LastFourSSN) < 4
THEN '0' + CAST(LastFourSSN AS VARCHAR(3))
ELSE CAST(LastFourSSN AS VARCHAR(4))
END LastFourSSN
FROM #t
If you are looking for converting values in the column for your purpose to use in application, you can use this following-
SELECT CAST(your_column AS VARCHAR(100))
--VARCHAR length based on your data
But if you are looking for change data type of your database column directly, you can try this-
ALTER TABLE TableName
ALTER COLUMN your_column VARCHAR(200) NULL
--NULL or NOT NULL based on the data already stored in database

How to specify input format in SQL create table?

I'm new in SQL and I need to create table with specified field format. How to add CHECK condition that will assure that input will be formatted e.g.
[LLLDD]
where L is a letter and D is a digit?
Try this if you are adding the constraint on a new table
CONSTRAINT ck_data_checker CHECK ([columnName] LIKE ('[A-Z][A-Z][A-Z][0-9][0-9]'))
Try this if you are adding the constraint on existing table
ALTER TABLE tableName
ADD CONSTRAINT ck_data_checker CHECK ([columnName] LIKE ('[A-Z][A-Z][A-Z][0-9][0-9]'))
Try this: http://sqlfiddle.com/#!6/3974b
create table test (
field1 char(5),
check (field1 like '[a-z][a-z][a-z][0-9][0-9]')
);
insert into test values ('ttt09'); --this will succeed
If you were to change the insert to:
insert into test values ('testi'); -- this will fail
insert into test values ('12345'); -- this will fail
I'm no sql server expert, but I think you can add a LIKE with a regular expression. Have a look at these websites
https://msdn.microsoft.com/en-us/library/ms179859.aspx
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/dc127433-2982-4065-b290-f411a075a694/use-regular-expressions-to-check-sql-server-2012-table-fields?forum=databasedesign

SQL Query Finding From Table DataType Declaration

I got some serial keys to find in sql database, such as “A-B-C”,”D-E-F”,”G-H-I”,”J-K-L” and they are stored in tblTemp using ntext data type. These above keys may store in three columns, colA, colB and colC (sometimes store in one column and the rest are null). Sometimes, two serial keys can find in one column (e.g. A-B-C;D-E-F) using “;” seperated. so i wrote the following sql query.
Declare #sa TABLE(var1 nvarchar(Max));
Insert INTO #sa(var1) VALUES (N’A-B-C’);
Insert INTO #sa(var1) VALUES (N’D-E-F’);
Insert INTO #sa(var1) VALUES (N’G-H-I’);
Insert INTO #sa(var1) VALUES (N’J-K-I’);
SELECT * FROM tblTemp
WHERE colA IN (SELECT var1 FROM #sa);
so i got the following error message.
The data types ntext and nvarchar(max) are incompatible in the equal to operator.
I still need to find for colB and colC. How should write query for this kind of situation?
all suggestions are welcome.
CAST/CONVERT (msdn.microsoft.com) your var1 to NTEXT type in your query so that the types are compatible.
SELECT
*
FROM
tblTemp
WHERE
colA IN (
SELECT
CAST(var1 AS NTEXT)
FROM
#sa
);
You have to convert/cast your search term as an appropriate data type, in this case text.
Try this:
Declare #sa TABLE(var1 nvarchar(Max));
Insert INTO #sa(var1) VALUES (N’A-B-C’);
Insert INTO #sa(var1) VALUES (N’D-E-F’);
Insert INTO #sa(var1) VALUES (N’G-H-I’);
Insert INTO #sa(var1) VALUES (N’J-K-I’);
SELECT *
FROM tblTemp t
WHERE EXISTS (SELECT 1
FROM #sa s
WHERE t.colA like cast('%'+s.var1+'%' as text)
OR t.colB like cast('%'+s.var1+'%' as text)
OR t.colC like cast('%'+s.var1+'%' as text)
);
Since all suggestions are welcome.
How about change the datatype on tblTemp to NVARCHAR(MAX)?
NTEXT was deprecated with the introduction of NVARCHAR(MAX) in 2005.
ALTER TABLE tblTemp ALTER COLUMN colA NVARCHAR(MAX)

SQL Server 2012 sequence

I create a table and sequence in order to replace identity in the table I use SQL Server 2012 Express but I get this error while I tried to insert data to the table
Msg 11719, Level 15, State 1, Line 2
NEXT VALUE FOR function is not allowed in check constraints, default objects, computed columns,
views, user-defined functions, user-defined aggregates, user-defined
table types, sub-queries, common table expressions, or derived
tables.
T-SQL code:
insert into Job_Update_Log(log_id, update_reason, jobid)
values((select next value for Job_Log_Update_SEQ),'grammer fixing',39);
This is my table:
create table Job_Update_Log
(
log_id int primary key ,
update_reason nvarchar(100) ,
update_date date default getdate(),
jobid bigint not null,
foreign key(jobid) references jobslist(jobid)
);
and this is my sequence:
CREATE SEQUENCE [dbo].[Job_Log_Update_SEQ]
AS [int]
START WITH 1
INCREMENT BY 1
NO CACHE
GO
Just get rid of the subselect in the VALUES section, like this:
insert into Job_Update_Log(log_id,update_reason,jobid)
values (next value for Job_Log_Update_SEQ,'grammer fixing',39);
Reference: http://msdn.microsoft.com/en-us/library/hh272694%28v=vs.103%29.aspx
Your insert syntax appears to be wrong. You are attempting to use a SELECT statement inside of the VALUES section of your query. If you want to use SELECT then you will use:
insert into Job_Update_Log(log_id,update_reason,jobid)
select next value for Job_Log_Update_SEQ,'grammer fixing',39;
See SQL Fiddle with Demo
I changed the syntax from INSERT INTO VALUES to INSERT INTO ... SELECT. I used this because you are selecting the next value of the sequence.
However, if you want to use the INSERT INTO.. VALUES, you will have to remove the SELECT from the query:
insert into Job_Update_Log(log_id,update_reason,jobid)
values(next value for Job_Log_Update_SEQ,'grammer fixing',39);
See SQL Fiddle with Demo
Both of these will INSERT the record into the table.
Try this one:
–With a table
create sequence idsequence
start with 1 increment by 3
create table Products_ext
(
id int,
Name varchar(50)
);
INSERT dbo.Products_ext (Id, Name)
VALUES (NEXT VALUE FOR dbo.idsequence, ‘ProductItem’);
select * from Products_ext;
/* If you run the above statement two types, you will get the following:-
1 ProductItem
4 ProductItem
*/
drop table Products_ext;
drop sequence idsequence;
------------------------------

SQL Server Concatenate string column value to 5 char long

Scenario:
I have a table1(col1 char(5)); A value in table1 may '001' or '01' or '1'.
Requirement:
Whatever value in col1, I need to retrive it in 5 char length concatenate with leading '0' to make it 5 char long.
Technique I applied:
select right(('00000' + col1),5) from table1;
I didn't see any reason, why it doesn't work? but it didn't.
Can anyone help me, how I can achieve the desired result?
Since you're using a fixed width column, it's already of size 5 (with whitespace). You need to trim it:
DECLARE #table1 TABLE (col1 char(5))
INSERT INTO #table1 (col1) VALUES ('12345')
INSERT INTO #table1 (col1) VALUES ('1')
SELECT RIGHT('00000'+RTRIM(col1),5) FROM #table1
-- Output:
-- 12345
-- 00001
Or use varchar instead:
DECLARE #table2 TABLE (col1 varchar(5))
INSERT INTO #table2 (col1) VALUES ('12345')
INSERT INTO #table2 (col1) VALUES ('1')
SELECT RIGHT('00000'+col1,5) FROM #table2
-- Output:
-- 12345
-- 00001
If you are storing the data in a CHAR field you are probably getting right spaces buffered with blanks. e.g. 01 = "01 ". If your do a RIGHT("00000" + value, 5) it'll still be the original value. You need to do a RTRIM() on the value or store the data in a VARCHAR field.
The problem is that the char(5) field is always 5 characters long, not matter what you put into it. If you insert '01' into the field, the value stored is actually '01 ' (note the trailing spaces).
Try this:
select right(('00000' + replace(col1, ' ', '')), 5)
Edit: I will leave my answer here as an example, but Michael's answer using rtrim is better.
you need to store your data in a consistent manner, so you don't need to write queries to format the data each time. this will fix your existing data:
UPDATE table1
SET col1= RIGHT('00000'+ISNULL(RTRIM(col1),''),5)
now every time you select you only have to do this:
SELECT col1 FROM table1
however, you must make sure that the data is formatted properly (leading zeros) every time it is inserted. I'd add a check constraint just to make sure:
ALTER TABLE table1 ADD CONSTRAINT
CK_table1_col1 CHECK (LEN(col1)=5)
and when you insert do this:
INSERT INTO table1
(col1, ...
VALUES
(RIGHT('00000'+ISNULL(RTRIM(#col1),''),5)