Calculate length of a SQLServer field

1
Hello, I have a table in SQL with the word column and a WordSize column, I was wondering if I have any way to register the word in the database and execute a function that calculates the amount of characters in this word to save in the WordSize column? / p>     
asked by anonymous 13.11.2016 / 20:55

2 answers

2

To check the number of characters:

SELECT LEN(COLUNA) FROM TABELA

To enter the number of characters of VALUE1 in COLUMN2 at insert time:

INSERT INTO TABELA (COLUNA1,COLUNA2)
VALUES ('VALOR1',LEN('VALOR1'))

If you want to do this after the data has already been entered:

UPDATE TABELA SET COLUNA2 = LEN(COLUNA1)
    
13.11.2016 / 21:30
2

Eduardo, there are two functions in SQL Server that return the size: Len () and DataLength () . And when you consult the documentation of the two functions, you will notice that there is a slight difference in behavior between them.

You can use a calculated column so that the word size is (re) calculated automatically.

-- código #1
USE tempDB;

CREATE TABLE Dic (
  palavra varchar(20),
  tamanhoDaPalavra as Len(palavra)
);

INSERT into Dic (palavra) values
  ('caminhão'), ('maçã'), ('trevo');

SELECT *
  from Dic; 

DROP TABLE Dic;
    
14.11.2016 / 15:54