Wednesday, February 27, 2013

find max length of a column

  hi , i  used to create VARCHAR(MAX) for columns when ever i see comments , text , one of my colleague told me its not always good idea to use VARCHAR(MAX) data type on columns like that ...
so i thought of finding the max length of the column and then decide how much length should i have to provide , so please find below
 
USE [tempdb]
GO
CREATE TABLE [dbo].[Test](
    [ID] INT IDENTITY(1,1) NOT NULL,
    [Name] [varchar](10) NULL
)

INSERT INTO Test (Name)
VALUES('NJ')


SELECT * FROM test

--Results
--ID  NAME
--1      NJ

 
  SELECT MAX(LEN(Name) )FROM test ---2
 
 
  INSERT INTO Test (Name)
VALUES('NewJersey')

 
    SELECT MAX(LEN(Name) )FROM test ---9

Based on the length we can decide how much max length we can give on a column ..
by doing this it could reduce space in  the memory allocation and beside  there are some cons also in this when we try top insert a row  with more than specified length it might get truncated, so please be careful to implement this

Thanks

 

No comments:

Post a Comment

https://blog.sqlauthority.com/2009/06/27/sql-server-fix-error-17892-logon-failed-for-login-due-to-trigger-execution-changed-database-context...