How to input the value 'NULL' into nvarchar column in SQL Server? - sql

I have a requirement to insert the literal value 'NULL' into a nvarchar column as a default value. But when I insert records the default is going as db NULL instead of the literal 'NULL'. Can someone tell me where I am going wrong?

So you want the actual string of "NULL" to be inserted? Try something like this:
create table NullTable
(
nvarchar(100) not null default 'NULL',
.... -- your other fields
)
EDIT: Here is a full solution
create table InsertNull
(
Nullfield nvarchar(100) not null default 'NULL',
someint int not null
)
go
insert into insertnull(someint)
select 20
select *
from InsertNull

Note the quotes:
INSERT INTO yourtable (varcharfield) VALUES ('NULL'); // string null
INSERT INTO yourtable (varcharfield) VALUES (NULL); // actual null

If set the default in code instead of the designer is should work.
ALTER TABLE [myTable] ADD DEFAULT ('NULL') FOR [TextColumn]

Related

What means DEFAULT VALUES specification in an insert query?

I am pretty new in Microsoft SQL Server and I am not so into DB in general.
I have the following doubt about an insert query that begin in this way:
insert into MyTable DEFAULT VALUES
What exactly mean the DEFAULT VALUES specification?
Tnx
Andrea
Reading the fine manual yields:
DEFAULT VALUES
Forces the new row to contain the default values defined for each column.
Well it uses the default values specified in your table.
So for example if you have a column CreationDate datetime default(getdate()) it will use it.
If each of the required columns in MyTable has specified DEFAULT VALUE then this statement insert such a row.
For example you could have column Date with default 01/01/2014 and position with DEFAULT 'Developer' and this statement would insert such a record.
You can read more here: http://msdn.microsoft.com/en-us/library/aa933206%28SQL.80%29.aspx
You can watch default specifications in work by checking that code:
DECLARE #tmp as table
(
id int null,
num int null default(777),
txt varchar(10) null default('abc'),
date datetime null
)
insert into #tmp DEFAULT VALUES
select * from #tmp
Output is
id num txt date
NULL 777 abc NULL

Insert null/empty value in sql datetime column by default

How do I create a table in SQL server with the default DateTime as empty, not 1900-01-01 00:00:00.000 that I get?
I mean, if there is no value inserted, the default value should be null, empty, etc.
if there is no value inserted, the default value should be null,empty
In the table definition, make this datetime column allows null, be not defining NOT NULL:
...
DateTimeColumn DateTime,
...
I HAVE ALLOWED NULL VARIABLES THOUGH.
Then , just insert NULL in this column:
INSERT INTO Table(name, datetimeColumn, ...)
VALUES('foo bar', NULL, ..);
Or, you can make use of the DEFAULT constaints:
...
DateTimeColumn DateTime DEFAULT NULL,
...
Then you can ignore it completely in the INSERT statement and it will be inserted withe the NULL value:
INSERT INTO Table(name, ...)
VALUES('foo bar', ..);
Even if your column is nullable, inserting an empty string will set the value to 1900-01-01 00:00:00.000. Make you insert real nulls not strings, then the db will store a null.
define it like your_field DATETIME NULL DEFAULT NULL
dont insert a blank string, insert a NULL INSERT INTO x(your_field)VALUES(NULL)
Ozi, when you create a new datetime object as in
datetime foo = new datetime();
foo is constructed with the time datetime.minvalue()
in building a parameterized query, you could check to see if the values entered are equal to datetime.minvalue()
-Just a side thought. seems you have things working.
I was having the same issue this morning. It appears that for a DATE or DATETIME field, an empty value cannot be inserted. I got around this by first checking for an empty value (mydate = "") and if it was empty setting mydate = "NULL" before insert.
The DATE and DATETIME fields don't behave in the same way as VARCHAR fields.
you can use like this:
string Log_In_Val = (Convert.ToString(attenObj.Log_In) == "" ? "Null" + "," : "'" + Convert.ToString(attenObj.Log_In) + "',");

TSQL Insert the column default value from Case Statement

I'd like to use the column's default value in an stored procedure insert, so that I don't have to repeat the default value in multiple places (it could change... DRY principle).
The T-SQL INSERT operation has a handy 'default' keyword that I can use as follows:
Declare #newA varchar(10)
Set #newA = 'Foo2'
-- I can use "default" like so...
Insert into Table_1 (
A,
B)
Values (
#newA,
default)
However, If I need to do something conditional, I can't seem to get the case statement to return 'default'.
-- How do I use 'default' in a case statement?
INSERT INTO Table_1 (
A,
B )
VALUES (
#newA,
CASE WHEN (#newA <> 'Foo2') THEN 'bar' ELSE default END)
-- > yeilds "Incorrect syntax near the keyword 'default'."
I could insert the default, and then update as needed like so:
INSERT INTO Table_1 (
A,
B )
VALUES (
#newA,
default)
UPDATE Table_1
SET B = CASE WHEN (A <> 'Foo2') THEN 'bar' ELSE B END
WHERE ID = SCOPE_IDENTITY()
But I'd really like somebody to tell me "There's a better way..."
Here's a table definition for this example if it helps...
CREATE TABLE dbo.Table_1 (
ID int NOT NULL IDENTITY (1, 1),
A varchar(10) NULL,
B varchar(10) NULL )
GO
ALTER TABLE dbo.Table_1 ADD CONSTRAINT DF_Table_1_A DEFAULT 'A-Def' FOR A
GO
ALTER TABLE dbo.Table_1 ADD CONSTRAINT DF_Table_1_B DEFAULT 'B-Def' FOR B
GO
default only works from within a VALUES() block, which does not seem to be an acceptable value in a CASE statement; you could use an if statement to determine what to insert:
DECLARE #newA varchar(10) = 'Foo2'
IF (#newA <> 'Foo2')
BEGIN
INSERT INTO Table_1 (A, B)
SELECT #newA, 'bar'
END
ELSE
BEGIN
--If you are using default values, you do not have to specify the column
INSERT INTO Table_1 (A)
SELECT #newA
END
I think this is better than updating after an insert, so that you only insert correct data into your table. It also keeps the number of INSERTS/UPDATES to 1. You should also be careful when you using ##IDENTITY due to scoping. Consider looking into SCOPE_IDENTITY().

Column name or number of supplied values does not match table definition

In the SQL Server, I am trying to insert values from one table to another by using the below query:
delete from tblTable1
insert into tblTable1 select * from tblTable1_Link
I am getting the following error:
Column name or number of supplied values does not match table definition.
I am sure that both the tables have the same structure, same column names and same data types.
They don't have the same structure... I can guarantee they are different
I know you've already created it... There is already an object named ‘tbltable1’ in the database
What you may want is this (which also fixes your other issue):
Drop table tblTable1
select * into tblTable1 from tblTable1_Link
I want to also mention that if you have something like
insert into blah
select * from blah2
and blah and blah2 are identical keep in mind that a computed column will throw this same error...
I just realized that when the above failed and I tried
insert into blah (cola, colb, colc)
select cola, colb, colc from blah2
In my example it was fullname field (computed from first and last, etc)
for inserts it is always better to specify the column names see the following
DECLARE #Table TABLE(
Val1 VARCHAR(MAX)
)
INSERT INTO #Table SELECT '1'
works fine, changing the table def to causes the error
DECLARE #Table TABLE(
Val1 VARCHAR(MAX),
Val2 VARCHAR(MAX)
)
INSERT INTO #Table SELECT '1'
Msg 213, Level 16, State 1, Line 6
Insert Error: Column name or number of
supplied values does not match table
definition.
But changing the above to
DECLARE #Table TABLE(
Val1 VARCHAR(MAX),
Val2 VARCHAR(MAX)
)
INSERT INTO #Table (Val1) SELECT '1'
works. You need to be more specific with the columns specified
supply the structures and we can have a look
The problem is that you are trying to insert data into the database without using columns. SQL server gives you that error message.
Error: insert into users values('1', '2','3') - this works fine as long you only have 3 columns
If you have 4 columns but only want to insert into 3 of them
Correct: insert into users (firstName,lastName,city) values ('Tom', 'Jones', 'Miami')
Beware of triggers. Maybe the issue is with some operation in the trigger for inserted rows.
Dropping the table was not an option for me, since I'm keeping a running log. If every time I needed to insert I had to drop, the table would be meaningless.
My error was because I had a couple columns in the create table statement that were products of other columns, changing these fixed my problem. eg
create table foo (
field1 as int
,field2 as int
,field12 as field1 + field2 )
create table copyOfFoo (
field1 as int
,field2 as int
,field12 as field1 + field2) --this is the problem, should just be 'as int'
insert into copyOfFoo
SELECT * FROM foo
The computed columns make the problem.
Do not use SELECT *. You must specify each fields after SELECT except computed fields
some sources for this issues are as below
1- Identity column ,
2- Calculated Column
3- different structure
so check those 3 , i found my issue was the second one ,
For me the culprit is int value assigned to salary
Insert into Employees(ID,FirstName,LastName,Gender,Salary) values(3,'Canada', 'pa', 'm',15,000)
in salary column When we assign 15,000 the compiler understand 15 and 000.
This correction works fine for me.
Insert into Employees(ID,FirstName,LastName,Gender,Salary) values(4,'US', 'sam', 'm',15000)
Update to SQL server 2016/2017/…
We have some stored procedures in place to import and export databases.
In the sp we use (amongst other things) RESTORE FILELISTONLY FROM DISK where we create a
table "#restoretemp" for the restore from file.
With SQL server 2016, MS has added a field SnapshotURL nvarchar(360) (restore url Azure) what has caused the error message.
After I have enhanced the additional field, the restore has worked again.
Code snipped (see last field):
SET #query = 'RESTORE FILELISTONLY FROM DISK = ' + QUOTENAME(#BackupFile , '''')
CREATE TABLE #restoretemp
(
LogicalName nvarchar(128)
,PhysicalName nvarchar(128)
,[Type] char(1)
,FileGroupName nvarchar(128)
,[Size] numeric(20,0)
,[MaxSize] numeric(20,0)
,FileID bigint
,CreateLSN numeric(25,0)
,DropLSN numeric(25,0) NULL
,UniqueID uniqueidentifier
,ReadOnlyLSN numeric(25,0)
,ReadWriteLSN numeric(25,0)
,BackupSizeInByte bigint
,SourceBlockSize int
,FilegroupID int
,LogGroupGUID uniqueidentifier NULL
,DifferentialBaseLSN numeric(25,0)
,DifferentialbaseGUID uniqueidentifier
,IsReadOnly bit
,IsPresent bit
,TDEThumbprint varbinary(32)
-- Added field 01.10.2018 needed from SQL Server 2016 (Azure URL)
,SnapshotURL nvarchar(360)
)
INSERT #restoretemp EXEC (#query)
SET #errorstat = ##ERROR
if #errorstat <> 0
Begin
if #Rueckgabe = 0 SET #Rueckgabe = 6
End
Print #Rueckgabe
Check your id. Is it Identity? If it is then make sure it is declared as ID not null Identity(1,1)
And before creating your table , Drop table and then create table.
The problem I had that caused this error was that I was trying to insert null values into a NOT NULL column.
I had the same problem, and the way I worked around it is probably not the best but it is working now.
It involves creating a linked server and using dynamic sql - not the best, but if anyone can suggest something better, please comment/answer.
declare #sql nvarchar(max)
DECLARE #DB_SPACE TABLE (
[DatabaseName] NVARCHAR(128) NOT NULL,
[FILEID] [smallint] NOT NULL,
[FILE_SIZE_MB] INT NOT NULL DEFAULT (0),
[SPACE_USED_MB] INT NULL DEFAULT (0),
[FREE_SPACE_MB] INT NULL DEFAULT (0),
[LOGICALNAME] SYSNAME NOT NULL,
[DRIVE] NCHAR(1) NOT NULL,
[FILENAME] NVARCHAR(260) NOT NULL,
[FILE_TYPE] NVARCHAR(260) NOT NULL,
[THE_AUTOGROWTH_IN_KB] INT NOT NULL DEFAULT(0)
,filegroup VARCHAR(128)
,maxsize VARCHAR(25)
PRIMARY KEY CLUSTERED ([DatabaseName] ,[FILEID] )
)
SELECT #SQL ='SELECT [DatabaseName],
[FILEID],
[FILE_SIZE_MB],
[SPACE_USED_MB],
[FREE_SPACE_MB],
[LOGICALNAME],
[DRIVE],
[FILENAME],
[FILE_TYPE],
[THE_AUTOGROWTH_IN_KB]
,filegroup
,maxsize FROM OPENQUERY('+ QUOTENAME('THE_MONITOR') + ','''+ ' EXEC MASTER.DBO.monitoring_database_details ' +''')'
exec sp_executesql #sql
INSERT INTO #DB_SPACE(
[DatabaseName],
[FILEID],
[FILE_SIZE_MB],
[SPACE_USED_MB],
[FREE_SPACE_MB],
[LOGICALNAME],
[DRIVE],
[FILENAME],
[FILE_TYPE],
THE_AUTOGROWTH_IN_KB,
[filegroup],
maxsize
)
EXEC SP_EXECUTESQL #SQL
This is working for me now.
I can guarantee the number of columns and type of columns returned by the stored procedure are the same as in this table, simply because I return the same table from the stored procedure.
In my case, I had:
insert into table1 one
select * from same_schema_as_table1 same_schema
left join...
and I had to change select * to select same_schema.*.
You're missing column name after TableName in insert query:
INSERT INTO TableName**(Col_1,Col_2,Col_3)** VALUES(val_1,val_2,val_3)
In my case the problem was that the SP I was executing returned two result sets, and only the second result set was matching the table definition.

SQL Server 2000 - Default Value for varchar fields

I have a sql server nvarchar field with a "Default Value or Binding" of empty string. It also happens to be a not null field.
Does this mean that there is no default or that it is a default of a string with no characters in it.
If I don't insert a value, will it insert with an empty string or fail with a "not null" error?
The default is a blank (empty) string.
If you don't provide a value, the insert will be successful and the value will be blank, not null.
Its the same as (assuming data is the col in question):
create table #t (id int, data varchar(100) not null default(''))
So:
insert into #t (id) values (1)
insert into #t (id,data) values (2,default)
insert into #t (id,data) values (3, 'allowed')
select * from #t
will return
1
2
3 allowed
and ..
insert into #t (id,data) values (1, null)
-- will error
If you have a true empty string as a default, then it will autopopulate with a 0 length string.
You should be careful to ensure it is a 0 length string and not nothing though. If for instance you are looking in the table builder gui for SSMS and it shows a blank for "Default Value or Binding", that means that there is no default value and an insert will fail if it is not populated. If you want it to have a 0 length string, populate it with '' (two single-quotes together with nothing in between.)
Default value for a column is just that - sql server will put that value when you dont supply one for the column. The value in the column will be an empty string. Not null error will not happen