Mega Code Archive

 
Categories / MSSQL Tutorial / Insert Delete Update
 

Use declared variables in insert statement

2> 3> 4> IF EXISTS(SELECT name FROM sys.tables 5>     WHERE name = 'T') 6>     DROP TABLE T 7> GO 1> 2> CREATE TABLE T ( 3>     c1 int, 4>     c2 varchar(8000) 5> ) 6> GO 1> 2> DECLARE @v1 varchar(max) 3> 4> SET @v1 = REPLICATE('A',7999) + 'B' 5> INSERT T VALUES (1, @v1) 6> SELECT RIGHT(c2,2) 'Right 2 of c2' FROM T 7> 8> SET @v1 = @v1 + 'B' 9> INSERT T VALUES (2, @v1) 10> SELECT RIGHT(c2,2) 'Right 2 of c2' FROM T 11> 12> GO (1 rows affected) Right 2 of c2 ------------- AB Msg 8152, Level 16, State 10, Server J\SQLEXPRESS, Line 9 String or binary data would be truncated. The statement has been terminated. (1 rows affected) Right 2 of c2 ------------- AB (1 rows affected) 1> 2> select * from t; 3> GO c1          c2 ----------- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------           1 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAB (1 rows affected) 1> 2> drop table t; 3> GO