Sql Server - Does checking for field NOT work if to avoid select?

Asked

Viewed 412 times

0

Please consider the script below..

He checks if there’s such a thing in a table, if there is one, he selects it. Then check again if it exists (only for didactic fims ;) and existing Dropa the column.

All right till then. Now comes the problem..

Do we get someone to run the script again? In theory, the field no longer exists, so it will not execute it nor select it or retry the right drop?

WRONG

If you run only the first part, you will see that from the error in select saying that the column does not exist (the check did not do anything) Now if you run the second part, it works! it DOES NOT attempt to drop since the column does not exist.

Now see the question.. how do I get to run this script N times without returning error?

IF EXISTS (SELECT 1
             FROM INFORMATION_SCHEMA.COLUMNS
            WHERE COLUMNS.TABLE_NAME = 'TabelaTal'
              AND COLUMNS.COLUMN_NAME = 'campoTal') 
begin
   select campoTal from TabelaTal;   
end;

IF EXISTS (SELECT 1
             FROM INFORMATION_SCHEMA.COLUMNS
            WHERE COLUMNS.TABLE_NAME = 'TabelaTal'
              AND COLUMNS.COLUMN_NAME = 'campoTal') 
begin
   ALTER TABLE TabelaTal DROP COLUMN campoTal;   
end;
  • Change your IF for IF COL_LENGTH('TabelaTal' , 'campoTal' ) IS NOT NULL

2 answers

0

Maybe you can solve using the sp_executesql function. As for example in INSERT below:

BEGIN
DECLARE
   @name VARCHAR(70) = 'San Francisco',
   @sql_stmt NVARCHAR(100) = 'INSERT INTO cities (name) VALUES (@name)'; 
    EXECUTE sp_executesql @sql_stmt, N'@name VARCHAR(70)', @name;
END;
GO

0

Friend, you can consult directly in the system tables of your SGDB. In the case of SQL Server it would be like this:

if exists(select column_name
          from mis.information_schema.columns
          where table_schema ='NOMEDOSCHEMA'
          and table_name = 'NOMEDATABELA'
          and column_name = 'NOMEDACOLUNA')
begin
   [SEU SELECT AQUI]
end

Hugs

Rauly Ambrosio

Browser other questions tagged

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