[SQL]sp_MSforeachdb Syntax Error, Msg 102 Level 15

2014-06-04

Situation:

It's been painful for me for a long time. I used to write a code to query Tables, Users, or something else. Sometimes are fine, sometime has errors showed up like below..


My example scripts like below
EXEC sp_MSforeachdb '
SELECT CASE WHEN ''?'' is NOT NULL THEN ''?'' ELSE ''NODANAME'' END AS [DBName],dp.name AS [UserName],USER_NAME(drm.role_principal_id) AS [AssociatedDBRole]
FROM ?.sys.database_principals dp
LEFT OUTER JOIN ?.sys.database_role_members drm
ON dp.principal_id=drm.member_principal_id
WHERE dp.sid NOT IN (0x01) AND dp.sid IS NOT NULL AND dp.is_fixed_role <> 1 AND dp.name NOT LIKE ''##%'' AND ''?'' NOT IN (''master'',''msdb'',''model'',''tempdb'') ORDER BY DBName'
After couple hours efforts, finally I found the solution

Solution:

Put [ ] to cover the ?
EX;

SELECT CASE WHEN ''?'' is NOT NULL THEN ''?'' ELSE ''NODANAME'' END AS [DBName],dp.name AS [UserName],USER_NAME(drm.role_principal_id) AS [AssociatedDBRole]
FROM [?].sys.database_principals dp
LEFT OUTER JOIN [?].sys.database_role_members drm
Newer Older