Procedure to delete a table

0

I did a stored procedure to delete a table if it exists that is passed by parameter, this is my code:

create procedure CrearTabla
@Tabla varchar (100)

as

if OBJECT_NAME(@tabla) is not null
   begin
      drop table @tabla
   end
go

But it does not work for me. Could you give me a hand? Thank you very much!

    
asked by GALS 06.11.2018 в 20:40
source

2 answers

1

To be able to do this, you need dynamic SQL (but please be careful with "SQL injection"):

CREATE PROCEDURE dbo.CrearTabla @Tabla varchar(100)
AS

DECLARE @sql nvarchar(300);

IF OBJECT_ID(@tabla, 'U') IS NOT NULL
BEGIN
    SET @sql = N'DROP TABLE ' + QUOTENAME(@Tabla);
    EXECUTE sp_executesql @sql;
END
    
answered by 06.11.2018 / 20:47
source
-2

details that I notice is missing an END to close the procedure. Besides, you should ask if there is such a table.

I will recreate the procedure as I think it should work.

CREATE PROCEDURE CrearTabla
@Tabla varchar (100)

as

  IF(@Tabla IS NOT NULL)
  BEGIN
    DROP TABLE IF EXISTS @tabla
  END
END
    
answered by 06.11.2018 в 20:53