Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define varchar with variable length

I am attempting to modify the datatype of a specific column in a specific table in a SQL Server 2012 database. in the beginning of the script, the user will be setting the new desired length of the column datatype. However when I attempt to alter the column in the table to set the new varchar length I am getting an error.

Here is the code snippet and the resulting error:

Declare @newPrecis int

Set @newPrecis = 23 -- New length of the index

Alter Table [dbo].[VTAB0047] Alter Column VAL varchar(@newPrecis)

Error:

Msg 102, Level 15, State 1, Line 5
Incorrect syntax near '@newPrecis'.

Currently the length of the VAL column is varchar(20) and I'd like it to be set to a length of 23 or whatever length is inputted in the set statement.

I'm ignoring any type of error checking at the moment because I'm simply trying to get the basic functionality down.

like image 994
вʀaᴎᴅᴏƞ вєнᴎєƞ Avatar asked Mar 24 '15 17:03

вʀaᴎᴅᴏƞ вєнᴎєƞ


People also ask

How define VARCHAR size?

The size of the maximum size (m) parameter of a VARCHAR column can range from 1 to 255 bytes. If you are placing an index on a VARCHAR column, the maximum size is 254 bytes. You can store character strings that are shorter, but not longer, than the m value that you specify.

Do I need to specify VARCHAR length in SQL?

The answer is you don't need to, it's optional. It's there if you want to ensure that strings do not exceed a certain length.

What is VARCHAR length as '- 1 in SQL?

varchar [ ( n | max ) ] Variable-length, non-Unicode character data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. So -1 isn't technically valid.

What is the length of VARCHAR 255?

VARCHAR(255) stores 255 characters, which may be more than 255 bytes.


2 Answers

if you want to be able to change the length of a varchar column dynamically then use dynimic sql, because varchar(n) does not allow parameters for n:

declare @sql varchar(500);
Declare @newPrecis int
Set @newPrecis = 23 --or any other value 

set @sql='Alter Table [dbo].[VTAB0047] Alter Column VAL varchar('+cast(@newPrecis as varchar(2))'+')'
exec(@sql)

or you could directly use :

Alter Table [dbo].[VTAB0047] Alter Column VAL varchar(23)

Note: if your new value for n be less than old value then you may get String or binary data would be truncated error if you had value with the length greater than new value for length.

like image 173
nil Avatar answered Sep 21 '22 17:09

nil


Declare @newPrecis  int    
Declare @query varchar(max)

Set @newPrecis  = 23; -- New length of the index
set @query ='Alter Table [dbo].[VTAB0047] Alter COLUMN  VAL varchar('
  + Cast(@newPrecis  as varchar) +')'

 exec (@query)
like image 43
Ali Adravi Avatar answered Sep 23 '22 17:09

Ali Adravi