SELECT 'GRANT ' + database_permissions.permissio n_name +
CASE database_permissions.class_ desc
WHEN 'SCHEMA' THEN ' ON ' +schema_name(major_id)
WHEN 'OBJECT_OR_COLUMN' THEN
CASE WHEN minor_id = 0 THEN ' ON ' +object_name(major_id) COLLATE Latin1_General_CI_AS_KS_WS
ELSE ' ON ' +(SELECT object_name(object_id) + ' ('+ name + ')'
FROM sys.columns
WHERE object_id = database_permissions.major_id
AND column_id = database_permissions.minor_id) end
ELSE ''
END +
' TO ' + database_principals.name COLLATE Latin1_General_CI_AS_KS_WS
FROM sys.database_permissions
JOIN sys.database_principals
ON database_permissions.grantee_ principal_id = database_principals.principal_ id
LEFT JOIN sys.objects --left because it is possible that it is a schema
ON objects.object_id = database_permissions.major_id
WHERE permission_name in ('SELECT','INSERT','UPDATE',' DELETE','EXECUTE') AND database_principals.NAME = ''