Tuesday, April 10, 2012

MSSQL useful tips

MSSQL set null when value is not numeric in select query

SELECT CASE ISNUMERIC(column1) WHEN 1 THEN column1 ELSE NULL END FROM table1

SQL Server Error Messages - Msg 8152 - String or binary data would be truncated.  The statement has been terminated.

This error message is occurred when I tried to insert data to values from another table.It’s due to one column in the table that im inserting data have lesser length than other table column.(varchar(25) – varchar(max)).It couldn’t found previously because second table column I have used max length but when inserting data it filled with strings that contains more than 25 characters.

I found another command to skip that error and continue but its like a try catch statement without catch part(thanks yasindu bro for nice example).

SET ANSI_WARNINGS OFF

Need to use above command before inserting records.but sometimes it’s not working

Inserting multiple records to a table

This isn’t simple thing but I previously work with MySQL and that is different and we can’t use

INSERT INTO tblName (column1,column2)
VALUES
('Value1','value11'),
('Value2','value22'),
('Value3','value33')
INSERT INTO tblName (column1,column2)
select ‘Value1′,’Value11’
UNION ALL
select ‘Value2′,’Value22’
UNION ALL
select ‘Value3′,’Value33’