Search This Blog

 Execute Select Statement for multiple Database in MSSQL


DECLARE @rn INT = 1, @dbname varchar(MAX) = '';

WHILE @dbname IS NOT NULL 

BEGIN

    SET @dbname = (SELECT name FROM (SELECT name, ROW_NUMBER() OVER (ORDER BY name) rn 

        FROM sys.databases WHERE name NOT IN('master','tempdb')) t WHERE rn = @rn);


    IF @dbname <> '' AND @dbname IS NOT NULL

        EXECUTE ('use '+ @dbname+';


            /* Your script code here */

           SELECT

   DB_NAME() AS DatabaseName,p.name AS ExtendedPropertyName, p.value AS ExtendedPropertyValue

FROM sys.extended_properties AS p

WHERE  p.major_id=0 AND p.minor_id=0   AND p.class=0

ORDER BY  [Name] ASC;


        ');

    SET @rn = @rn + 1;

END;