30 October is a special holiday in my country.
I had to mark holiday in a certain table present
in any database.
I decided to use sp_msforeachdb
While trying to construct the expression , I found that I am unable
to surround a character with quote character.
I even tried using four quotes '''' but no success.
I gave up and used char(39) as a workaround.
here is the complete syntax
exec sp_MsForEachDb
'
if exists( select null from [?].sys.tables where name = ''alldates'' )
begin
print ''use '' + ''?'' +'' ''
+ '' update a set a.isholiday = '' + char(39)
+ ''Y'' + char(39)
+ '', a.holiday_name = '' + char(39)
+ ''Eid Milad'' + char(39)
+ '', a.gz_holiday ='' + char(39)
+ ''Y'' + char(39)
+ ''from alldates a where 1=1 and dt = ''
+ char(39) + ''2020/10/30'' + char(39)
end
'
the result will be
use sqlAuthority
update a
set a.isholiday = 'Y',
a.holiday_name = 'Eid Milad',
a.gz_holiday ='Y'
from alldates a
where 1=1
and dt = '2020/10/30'
Please note that If I replace char(39) with ''''
I don't get ' (quote) printed.
My Question
I must be missing some basics, please guide
how to print quote inside a print clause
Sorry, I mistakenly copied the code after it was PRINTed out and not the original code for inside the EXEC. This is the code that should be in the EXEC sp_msforeachdb:
...
begin
print ''use [?] ''
+ '' update a set a.isholiday = ''''Y''''''
+ '', a.holiday_name = ''''Eid Milad''''''
+ '', a.gz_holiday =''''Y''''''
+ ''from alldates a where 1=1 and dt = ''''2020/10/30''''''
...
so why do you want to print it again? to copy paste and run it? Maybe another approach with powershell
# ----------------------------------------------
Import-Module SqlPs -DisableNameChecking #may only need this line for SQL 2012 +
# $databases grabs list of databases from sys.databases
$server = 'your.server.name'
$databases = invoke-sqlcmd -ServerInstance $server -Database 'master' -Query "select name as DATABASENAME from sys.databases"
foreach ($database in $databases) #for each separate server / database pair in $databases
{
$DBname = $database.DATABASENAME #databasename from the select query
Write-Output $DBname
invoke-sqlcmd -ServerInstance $server -Database ${DBname} -InputFIle "C:\DBA_SCRIPTS\UpdateHoliday\SetEidMilad.sql"
} #end foreach loop