Showing posts with label SQL. Show all posts
Showing posts with label SQL. Show all posts

Wednesday, 8 August 2018

How to execute SQL against all DBs on a Server

One option is sp_MSForEachDB. It's undocumented but useful nonetheless

DECLARE @command varchar(1000) 
SELECT @command = 
 'USE [?] SELECT c.name AS ColName, t.name AS TableName FROM sys.columns c JOIN 
sys.tables t ON c.object_id = t.object_id WHERE c.name LIKE ''%BILLG_BIN_ID%''' 
EXEC sp_MSforeachdb @command
NOTES:
  1. ? is replaced in the query as the database name, so structure the query to explicitly define which DB it is to query against

Thursday, 16 April 2015

sql server sub query with a comma separated resultset

I have above table structure and if i want to show my child table's value comma separated then below is my solution.

 SELECT n.nominationID
        , SUBSTRING((
                            SELECT ',' + af.awardFocusName
                            FROM NominationAwardFocus naf
                            JOIN AwardFocus af
                                ON naf.awardFocusID = af.awardFocusID
                            WHERE n.nominationID = naf.nominationID
                            FOR XML PATH('')

                        ), 2, 1000000)
    FROM Nomination n

And another solutions is
DECLARE @listStr VARCHAR(MAX)
(SELECT @listStr = COALESCE(@listStr+',' , '') + c.Code FROM RefferalCPTCodes  r inner join CPTCode c on r.CPTCodeID=c.id where ReferralID=80) 
SELECT @listStr