Question

I have been making changes to a database and am creating a script so that it can be run on the original database to inherit all the changes I have made.

I need to alter the length of an NVARCHAR, but want to check its length before I alter the column. I am struggling with the syntax a bit, could anyone help me with this?

SELECT LEN(colName) AS MyLength FROM tblName
IF MyLength = 60
BEGIN
    ALTER TABLE tblName
    ALTER COLUMN colName nvarchar(140) NOT NULL
END
GO

If I attempt to run this query in SQL Server Management Studio I get an error message that says:

Invalid column name 'MyLength'.

Was it helpful?

Solution

try this:

IF (select max(LEN(colName)) from tblName) = 60
BEGIN
    ALTER TABLE tblName
    ALTER COLUMN colName nvarchar(140) NOT NULL
END
GO

OTHER TIPS

You need to define it as a variable

declare @i int
select @i = len(colname) from table

But this won't work anyway as it returns the length of the data, not the column, which being a varchar, is inherently variable. Try looking at the sysobjects and syscolumns tables or Information_Schema.Columns instead

Following up on podiluska's answer, the complete command you're looking for is:

IF (SELECT [CHARACTER_MAXIMUM_LENGTH] FROM INFORMATION_SCHEMA.COLUMNS WHERE [COLUMN_NAME] = 'ColumnName' AND [TABLE_NAME] = 'TableName') < 140
BEGIN
    ALTER TABLE [dbo].[TableName] ALTER COLUMN [ColumnName] NVARCHAR(140) NOT NULL
END

To reiterate, using MAX(LEN()) will only give you the length of the longest string in the column, not the maximum allowed length!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top