How to delete record from 2 tables where one contains the left 0 SQL SERVER

Asked

Viewed 119 times

0

I have 2 tables in which one is inserted the records that comes from a file txt and the other the records that comes from a file excel.

With this, I need to delete the records from the table txt containing in the table excel, in case the same.

Only that there are files in the table txt starting with 0 and in the table excel no, and the system does not understand as equal and does not exclude.

How can I also delete records that contain 0 at the beginning ?

My delete is like this:

DELETE 
TEMP_IMPORTACAO_TXT 
FROM 
TEMP_IMPORTACAO_TXT TXT 
INNER JOIN 
TEMP_IMPORTACAO_EXCEL EX 
ON 
TXT.CAMPO = EX.CAMPO
  • May or may not contain 1 or more 0 to the left?

  • How can a field have zero left in a database? The type is text(varchar,car...)?

  • Only 1 zero left. @DH.

  • @user5978 is varchar type

  • Regardless of the language, when you have two values represented as string, and you want to make a "numerical" comparison between these values, you should use a "CAST". Sqlserver implements this: http://blog.sqlauthority.com/2007/07/07/sql-server-convert-text-convert-to-numbers-integer-cast-and-convert/. I know they will answer your question, but please consider doing so.

1 answer

1


as I don’t know what kind of data you have in this field, it can be a string that has only numeric characters or not.

Then you can use substring to remove the zeros on the left, for example:

DECLARE @texto varchar(max);

SET @texto = '00000001A6F2B';
print SUBSTRING(@texto, PATINDEX('%[^0]%',@texto), LEN(@texto) - PATINDEX('%[^0]%',@texto) + 1)
--1A6F2B

your updated select would look like this:

DELETE 
TEMP_IMPORTACAO_TXT 
FROM 
TEMP_IMPORTACAO_TXT TXT 
INNER JOIN 
TEMP_IMPORTACAO_EXCEL EX 
ON 
SUBSTRING(TXT.CAMPO, PATINDEX('%[^0]%',TXT.CAMPO), LEN(TXT.CAMPO) - PATINDEX('%[^0]%',TXT.CAMPO) + 1) = EX.CAMPO

The only problem would be if the field has only '0', in this case you will need to make use of a case.

CASE WHEN PATINDEX('%[^0]%',@texto) = 0
    THEN '0'
    ELSE SUBSTRING(@texto, PATINDEX('%[^0]%',@texto), LEN(@texto) - PATINDEX('%[^0]%',@texto) + 1)
END
  • 2

    A CAST would be a better solution.

  • @user5978, this will depend on the content of its field, if it has any non-numeric character, the cast will break the script.

  • Maybe, but because I have zero left, and because this zero has to be ignored, I believe it is a column with only numbers. In fact, if that is the case, even CAST is not the best solution. It should be changing the column type :D

Browser other questions tagged

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