Calculate length of a Sqlserver field

Asked

Viewed 1,514 times

1

Hello, I have a table in SQL with the word column and a column sizeDaPalavra, I was wondering if you 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 column sizeDaPalavra?

  • how the column size is declared?

2 answers

2

Eduardo, there are two functions in SQL Server that return the size: Len() and Datalength(). And when you look at the documentation of the two functions, you’ll notice that there’s a slight difference in behavior between them.

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

-- 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;

2

To check the number of characters:

SELECT LEN(COLUNA) FROM TABELA

To insert the amount of VALOR1 characters in COLUNA2 at the time of the Insert:

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

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

UPDATE TABELA SET COLUNA2 = LEN(COLUNA1)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.