Dynamic SQL, Knowing if DB exists SQL 2008?

0

I raise my problem. I have a SQL Server 2008 Database Server in which new bases are constantly being created, many of them are also erasing them and I do not have full knowledge of how the logging works, because I can actually see which bases have been eliminated, but a while ago it stopped showing many, so I think that the LOG delete it or move it.

I would like a dynamic SQL where I indicate by any variable or cursor, all the bases that I want to consult if they exist and that for each one return the value "exists" or "does not exist".

I have nothing advanced since I can not think of how I could do it. I thought with some cursor along with a while, but it does not occur to me in truth.

Any idea how it could?

    
asked by Esteban Jaramillo 06.02.2018 в 15:10
source

2 answers

1

You can execute this:

declare @NombreBd varchar(50)
declare db cursor for
SELECT name FROM master.dbo.sysdatabases
open db
fetch next from db into @NombreBd
begin
    print @NombreBd
    fetch next from db into @NombreBd
    --Select o cualquier consulta con Exec(...)
end
deallocate db
    
answered by 06.02.2018 / 16:38
source
1

You can use a temporary table to have the names of the databases and from this make a query that you return what you need,

    CREATE TABLE #Tabla
    ( nombreDB    VARCHAR(30))

    SELECT 
         nombreDB,
        CASE 
            WHEN   name IS null  THEN 'NO Existe'
        ELSE   
           'Existe'
         END    AS  Estatus
   FROM master.dbo.sysdatabases    DB
   RIGHT JOIN   #Tabla             T
   ON   DB.name                     =               T.nombreDB

With this you can do an SP or a script according to what you need.

I hope it serves you.

    
answered by 06.02.2018 в 16:38