Can you Limit an nvarchar(max) field in SQL - sql-server

I know this can be set in the client/server, but is there a way to put a character limit on an nvarchar(max) field over 4000 characters. IE 20,000 characters?

As Sean hinted:
CREATE TABLE ImageTable (ImageID INT IDENTITY PRIMARY KEY
, ImageBinary VARBINARY(MAX) )
ALTER TABLE [dbo].ImageTable ADD CONSTRAINT [CX_ImageTable_Size]
CHECK ( DATALENGTH(ImageBinary) < 19999)
INSERT INTO dbo.ImageTable (ImageBinary ) values (0x0000000000000000001)
-- throws error if length is longer than constraint

Related

How to alter a column in HANA DB to be incremented, after that table was already created?

I want to have a table with this properties:
CREATE TABLE status
(
identificationnumber BIGINT NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
desc varchar(10)
);
Suddenly the production table was already created and has a enormous amount of data. Schema that is already in use:
CREATE TABLE status
(
identificationnumber BIGINT NOT NULL PRIMARY KEY,
desc varchar(10)
);
Is it possible to update the schema with an autoincrement?
Technically it is possible, but may depend on the size of data. You can check it by yourself at TEST/QAS system and then apply the change to production.
Here's the code I used:
/*Create example table*/
create column table tst_tab (
x int
);
/*Fill it with some data*/
insert into tst_tab
select 1 from dummy union all
select 2 from dummy union all
select 3 from dummy
;
/*Add identity column*/
alter table tst_tab
add(id int generated by default as identity);
/*Statement 'alter table tst_tab add(id int generated by default as identity)'
successfully executed in 14 ms 281 µs*/
/*Check results*/
select * from tst_tab;

Insert query, string or binary data would be truncated

Why does this keep happening? The first 2 data types are Int. The 'Games' is DateTime. The last is VarChar. Why is it not executing successfully
CREATE TABLE JaretSchedule
(
FieldID int Primary,
TeamID int Foreign,
Games DateTime,
TeamsPlaying varChar
);
INSERT INTO [dbo].[JaretsSchedule]
([FieldID]
,[TeamID]
,[Games]
,[TeamsPlaying])
VALUES('1', '1', '2012-01-20 12:00:00', 'Roadrunners v.s. Cheetahs');
Error Message: String or binary data would be truncated. The statement has been terminated
Because ,you have exceeded the max size of field,
ALTER TABLE JaretsSchedule ALTER COLUMN TeamsPlaying nvarchar(1000);
The default length of varchar when used as a column data type is 1.
varchar [ ( n | max ) ] Variable-size string data
. . .
When n isn't specified in a data definition or variable declaration
statement, the default length is 1. If n isn't specified when using
the CAST and CONVERT functions, the default length is 30.
char and varchar (Transact-SQL)
So you need so set a max length for the column. EG
use tempdb
go
drop table if exists JaretsSchedule
go
create table JaretsSchedule
(
FieldId int,
TeamID int,
Games datetime,
TeamsPlaying varchar(255)
)
go
insert into JaretsSchedule(FieldId,TeamID,Games,TeamsPlaying)
values (1,1,'2012-01-20 10:00:00','Roadrunnersv.s.Cheetahs')

Check Constraints in SQL

I want not to allow my DB user to enter bigger dates than 2017-03-18. How can add this constraint to my table?
Is this Correct?
(Year([ContractEnd])<2017) and (Month([ContractEnd])<03) and (Day([ContractEnd])<18)
You can add a constraint like that to an existing table like so:
alter table t add constraint chk_ContractEnd_lt_20170319
check (ContractEnd<'20170319');
rextester demo: http://rextester.com/FQWFMI88817
create table t (
id int not null identity(1,1)
, ContractEnd date
/* at table creation */
, constraint chk_ContractEnd_lt_20170319 check (ContractEnd<'20170319')
)
alter table t drop constraint chk_ContractEnd_lt_20170319;
/* to existing table */
alter table t add constraint chk_ContractEnd_lt_20170319
check (ContractEnd<='20170318');
insert into t values ('20161231')
insert into t values ('20170318')
/* all good */
insert into t values ('20170319')
/* -- Error, constraint violation */
Try
[ContractEnd] DATE CHECK ([ContractEnd] <= '20170318')

Customer email address

I am new to sql programming. This is for a homework assignment for my database class. I have made all the table I need for the assignment I am just hung up one part. The line in the homework reads as follows:
If type is 'faculty' the email address must end up with '#xxx.edu'
This is what the table looks like:
create table customer
(
CID# char(10) primary key IDENTITY (1,1) NOT NULL,
F_name varchar(20),
M_name varchar(20),
L_name varchar(20),
type varchar(20),
street varchar(20),
city varchar(20),
state varchar(20),
zip char(5),
password varchar (20) NOT NULL,
email varchar(20) NOT NULL
Constraint CK_customer_type check (type in ('student', 'faculty'))
)
Any help someone could lend would be greatly appreciated!
This constraint would check if the email column ends with #xxx.edu.
Constraint CK_email_faculty check (
type<>'faculty' OR
CHARINDEX('#xxx.edu',email)=LEN(email)-LEN('#xxx.edu')+1
)
Remark 1: Better than checking the type being appropriate in a CHECK constraint, make a table customer_type with possible types ('student', 'faculty' ...), and have a foreign key in customer pointing a the type.
CREATE TABLE customer_type(id INT NOT NULL PRIMARY KEY,desc VARCHAR(128));
INSERT INTO customer_type(id,desc)VALUES(1,'student');
INSERT INTO customer_type(id,desc)VALUES(2,'faculty');
Have a foreign key in your customer table to point to the customer_type table:
CREATE TABLE customer(
-- ...
type INT NOT NULL,
-- ...
CONSTRAINT FK_type_customer_type FOREIGN KEY(type) REFERENCES customer_type(id)
)
You would then not insert the type description but the type identifier:
INSERT INTO customer(...,type,...)VALUES(...,1,...); -- for student
INSERT INTO customer(...,type,...)VALUES(...,3,...); -- fails, type doesn't exist
That way you save disk space, and memory when these tables are cached by SQL Server.
Remark 2: The widths of your varchar fields are very small. An email address of only 20 characters?
For your particular case a constraint like this might be ok:
Constraint CK_customer_email check (
type <> 'faculty' OR
email LIKE '%_%#_%.edu'
CHARINDEX('#xxx.edu',email)=LEN(email)-LEN('#xxx.edu')+1
)
This will allow 1+ characters, followed by #, followed by 1+ characters, followed by .edu.
However, in real life (where mean people try to insert bad e-mail addresses), validation is more complex (not all characters are allowed), so a custom function can be used. One that seems to be almost complete is provided here:
CREATE FUNCTION [dbo].[fnAppEmailCheck](#email VARCHAR(255))
--Returns true if the string is a valid email address.
RETURNS bit
as
BEGIN
DECLARE #valid bit
IF #email IS NOT NULL
SET #email = LOWER(#email)
SET #valid = 0
IF #email like '[a-z,0-9,_,-]%#[a-z,0-9,_,-]%.[a-z][a-z]%'
AND LEN(#email) = LEN(dbo.fnAppStripNonEmail(#email))
AND #email NOT like '%#%#%'
AND CHARINDEX('.#',#email) = 0
AND CHARINDEX('..',#email) = 0
AND CHARINDEX(',',#email) = 0
AND RIGHT(#email,1) between 'a' AND 'z'
SET #valid=1
RETURN #valid
END
Then, your constraint would be like this:
Constraint CK_customer_email check (
type <> 'faculty' OR
[dbo].[fnAppEmailCheck] (email) = 1
)
Add Constraint
Constraint CK_email check (email like case when type in ('faculty') then '%#xxx.edu' else email end )

Store default sequence number in table without using any variable

I have one table in database which should contain sequence number.
create table SequenceNumber(
number int indentity(1,1) primary key
)
Now I want to store number from 1 to 1448 without setting IDENTITY_INSERT ON/OFF and without counter variable.
I need values from 1 to 1448 in 'number' column
can anyone tell me how can I do it?
yes you can do it as follow
just change the value 1448 as per your need
idea from here : http://www.codeproject.com/Tips/780441/Tricky-SQL-Questions
CREATE TABLE SequenceNumber(
NUMBER BIGINT IDENTITY(1,1) PRIMARY KEY
)
WHILE(1=1)
BEGIN
INSERT INTO SequenceNumber
DEFAULT VALUES
IF EXISTS(SELECT 1 FROM SequenceNumber WHERE NUMBER = 1448)
BREAK
END
SELECT NUMBER FROM SequenceNumber

Resources