MZ @ !L!This program cannot be run in DOS mode.
$ PE L @C ! @ ` y P K @ H .text `.rsrc @ @.reloc @ @ B H $ P ; k
er.log_ider.event_typeer.log_dateer.descriptioner.process_ider.mailitem_ider.account_ider.last_mod_dateer.last_mod_user
create table #tmp_sp_helpdiagrams
([Database] sysname not null, Name sysname not null, ID int not null, Owner sysname null, OwnerID int not null)
insert into #tmp_sp_helpdiagrams exec dbo.sp_helpdiagrams
drop table #tmp_sp_helpdiagrams
'Server[@Name=' + quotename(cast(serverproperty(N'Servername') as sysname),'''') +
']/Database[@Name=' + quotename(db_name(),'''') +
']/DatabaseDiagram[@Name=' + quotename(tshd.Name,'''') + ' and @OwnerID=' + quotename(cast(tshd.OwnerID as nvarchar(30)),'''') + ']'
tshd.Nametshd.IDtshd.Ownertshd.OwnerID
CREATE TABLE #tmp_computed_field(
ComputedFieldId int,
NotificationClassId int,
FieldName nvarchar(255),
SqlExpression nvarchar(4000),
FieldDigestGrouping bit
)
INSERT #tmp_computed_field EXEC [SchemaPrefix].NSGetComputedFields
DROP TABLE #tmp_computed_field
cf.ComputedFieldIdcf.NotificationClassIdcf.FieldNamecf.SqlExpressioncf.FieldDigestGrouping
CREATE TABLE #tmp_notification_field(
NotificationFieldId int,
NotificationClassId int,
FieldName nvarchar(255),
FieldType nvarchar(255),
FieldDigestGrouping bit
)
INSERT #tmp_notification_field EXEC [SchemaPrefix].NSGetNotificationFields
DROP TABLE #tmp_notification_field
nf.NotificationFieldIdnf.NotificationClassIdnf.FieldNamenf.FieldTypenf.FieldDigestGrouping
CREATE TABLE #tmp_event_field(
EventFieldId int,
EventClassId int,
FieldName nvarchar(255),
FieldType nvarchar(255),
FieldTypeMods nvarchar(255)
)
INSERT #tmp_event_field EXEC [SchemaPrefix].NSGetEventFields
DROP TABLE #tmp_event_field
ef.EventFieldIdef.EventClassIdef.FieldNameef.FieldTypeef.FieldTypeMods
CREATE TABLE #tmp_subscription_chronicle(
SubscriptionChronicleId int,
ChronicleName nvarchar(255),
SubscriptionClassId int,
SqlStatementsXml nvarchar(max)
)
INSERT #tmp_subscription_chronicle EXEC [SchemaPrefix].NSGetSubscriptionChronicles
DROP TABLE #tmp_subscription_chronicle
sch.SubscriptionChronicleIdsch.SubscriptionClassIdsch.ChronicleNamenullsch.SqlStatementsXml
9
CREATE TABLE #tmp_condition_scheduled_rule(
RuleId int,
RuleName nvarchar(255),
RuleType tinyint,
Action ntext,
ActionTimeout int,
EventClassId int,
SubscriptionClassId int,
EventClassName nvarchar(255),
InputTypeName nvarchar (128),
InputTypeSchema nvarchar (128),
SqlUserName nvarchar (128),
SqlLoginName nvarchar (128)
)
INSERT #tmp_condition_scheduled_rule EXEC [SchemaPrefix].NSGetRulesOnType @RuleType = 4
DROP TABLE #tmp_condition_scheduled_rule
csr.RuleIdcsr.RuleNamecsr.Actioncsr.ActionTimeoutcsr.SubscriptionClassIdcsr.InputTypeNamecsr.InputTypeSchemacsr.SqlUserNamecsr.SqlLoginName
)
CREATE TABLE #tmp_subscription_scheduled_rule(
RuleId int,
RuleName nvarchar(255),
RuleType tinyint,
Action ntext,
ActionTimeout int,
EventClassId int,
SubscriptionClassId int,
EventClassName nvarchar(255),
InputTypeName nvarchar (128),
InputTypeSchema nvarchar (128),
SqlUserName nvarchar (128),
SqlLoginName nvarchar (128)
)
INSERT #tmp_subscription_scheduled_rule EXEC [SchemaPrefix].NSGetRulesOnType @RuleType = 2
DROP TABLE #tmp_subscription_scheduled_rule
ssr.RuleIdssr.RuleNamessr.SubscriptionClassIdssr.Actionssr.ActionTimeoutssr.EventClassId
CREATE TABLE #tmp_condition_event_rule(
RuleId int,
RuleName nvarchar(255),
RuleType tinyint,
Action ntext,
ActionTimeout int,
EventClassId int,
SubscriptionClassId int,
EventClassName nvarchar(255),
InputTypeName nvarchar (128),
InputTypeSchema nvarchar (128),
SqlUserName nvarchar (128),
SqlLoginName nvarchar (128)
)
INSERT #tmp_condition_event_rule EXEC [SchemaPrefix].NSGetRulesOnType @RuleType = 3
DROP TABLE #tmp_condition_event_rule
cer.RuleIdcer.RuleNamecer.Actioncer.ActionTimeoutcer.EventClassNamecer.SubscriptionClassIdcer.InputTypeNamecer.InputTypeSchemacer.SqlUserNamecer.SqlLoginName
CREATE TABLE #tmp_subscription_event_rule(
RuleId int,
RuleName nvarchar(255),
RuleType tinyint,
Action ntext,
ActionTimeout int,
EventClassId int,
SubscriptionClassId int,
EventClassName nvarchar(255),
InputTypeName nvarchar (128),
InputTypeSchema nvarchar (128),
SqlUserName nvarchar (128),
SqlLoginName nvarchar (128)
)
INSERT #tmp_subscription_event_rule EXEC [SchemaPrefix].NSGetRulesOnType @RuleType = 1
DROP TABLE #tmp_subscription_event_rule
ser.RuleIdser.RuleNameser.Actionser.ActionTimeoutser.EventClassNameser.SubscriptionClassId
CREATE TABLE #tmp_subscription_field(
SubscriptionFieldId int,
SubscriptionClassId int,
FieldName nvarchar(255),
FieldType nvarchar(255),
FieldTypeMods nvarchar(255)
)
INSERT #tmp_subscription_field EXEC [SchemaPrefix].NSGetSubscriptionFields
DROP TABLE #tmp_subscription_field
sf.SubscriptionFieldIdsf.SubscriptionClassIdsf.FieldNamesf.FieldTypesf.FieldTypeMods
CREATE TABLE #tmp_subscription_class(
SubscriptionClassId int,
SubscriptionClassName nvarchar(255),
FileGroup nvarchar(128),
IndexSqlStatementsXml nvarchar(max)
)
INSERT #tmp_subscription_class EXEC [SchemaPrefix].NSGetSubscriptionClasses
DROP TABLE #tmp_subscription_class
sc.SubscriptionClassIdsc.SubscriptionClassNamesc.FileGroupnullsc.IndexSqlStatementsXml
-
CREATE TABLE #tmp_protocol_field(
ProtocolFieldId int,
NotificationClassProtocolId int,
FieldName nvarchar(255),
FieldReference nvarchar(255),
SqlExpression nvarchar(4000)
)
INSERT #tmp_protocol_field EXEC [SchemaPrefix].NSGetProtocolFields
DROP TABLE #tmp_protocol_field
pf.FieldNamepf.ProtocolFieldIdpf.NotificationClassProtocolIdpf.SqlExpressionpf.FieldReference
CREATE TABLE #tmp_protocol_retry_schedule(
ProtocolRetryScheduleId int,
NotificationClassProtocolId int,
IntervalOrdinal tinyint,
Interval int
)
INSERT #tmp_protocol_retry_schedule EXEC [SchemaPrefix].NSGetProtocolRetrySchedules
DROP TABLE #tmp_protocol_retry_schedule
prs.ProtocolRetryScheduleIdprs.NotificationClassProtocolIdprs.Intervalprs.IntervalOrdinal
CREATE TABLE #tmp_protocols(
NotificationClassProtocolId int,
NotificationClassProtocolName nvarchar(255),
NotificationClassId int,
FailureEventLogInterval int,
FailuresBeforeEventLog int,
FailuresBeforeAbort int,
MulticastRecipientLimit int,
WorkItemTimeout int
)
INSERT #tmp_protocols EXEC [SchemaPrefix].NSGetNotificationClassProtocols
DROP TABLE #tmp_protocols
p.NotificationClassProtocolNamep.NotificationClassProtocolIdp.NotificationClassIdp.FailureEventLogIntervalp.FailuresBeforeEventLogp.FailuresBeforeAbortp.MulticastRecipientLimitp.WorkItemTimeout
CREATE TABLE #tmp_content_formatter_argument(
ContentFormatterArgumentId int,
ContentFormatterId int,
ArgumentName nvarchar(255),
ArgumentValue nvarchar(4000)
)
INSERT #tmp_content_formatter_argument EXEC [SchemaPrefix].NSGetContentFormatterArguments
DROP TABLE #tmp_content_formatter_argument
cfa.ArgumentNamecfa.ArgumentValuecfa.ContentFormatterArgumentIdcfa.ContentFormatterId
CREATE TABLE #tmp_content_formatter(
ContentFormatterId int,
NotificationClassId int,
ClassName nvarchar(255),
AssemblyName nvarchar(max)
)
INSERT #tmp_content_formatter EXEC [SchemaPrefix].NSGetContentFormatter
DROP TABLE #tmp_content_formatter
cf.ClassNamecf.ContentFormatterIdcf.AssemblyNamecf.NotificationClassId
l
CREATE TABLE #tmp_notification_class(
NotificationClassId int,
NotificationClassName nvarchar(255),
DigestDelivery bit,
MulticastDelivery bit,
ExpirationAge int,
FileGroup nvarchar(128),
NotificationBatchSize int,
ContentFormatterId int,
ClassName nvarchar(255),
AssemblyName nvarchar (260)
)
INSERT #tmp_notification_class EXEC [SchemaPrefix].NSGetNotificationClasses
DROP TABLE #tmp_notification_class
nc.NotificationClassNamenc.NotificationClassIdnc.DigestDeliverync.MulticastDeliverync.ExpirationAgenc.NotificationBatchSizenc.FileGroupnc.ContentFormatterIdnc.ClassNamenc.AssemblyName
CREATE TABLE #tmp_hosted_event_provider_argument(
ProviderArgumentId int,
ProviderId int,
ArgumentName nvarchar(255),
ArgumentValue nvarchar(4000)
)
INSERT #tmp_hosted_event_provider_argument EXEC [SchemaPrefix].NSGetProviderArguments
DROP TABLE #tmp_hosted_event_provider_argument
hepa.ArgumentNamehepa.ProviderArgumentIdhepa.ProviderIdhepa.ArgumentValue
CREATE TABLE #tmp_hosted_event_provider(
ProviderId int,
ProviderName nvarchar(255),
ProviderClassName nvarchar(255),
AssemblyName nvarchar(260),
SystemName nvarchar(255),
StartTime datetime,
Interval int,
Timeout int,
ActivationState tinyint
)
INSERT #tmp_hosted_event_provider EXEC [SchemaPrefix].NSGetProviders 'HostedOnly'
DROP TABLE #tmp_hosted_event_provider
hep.ProviderNamehep.ProviderIdhep.ProviderClassNamehep.AssemblyNamehep.SystemNamehep.StartTimehep.Intervalhep.Timeouthep.ActivationState
!
CREATE TABLE #tmp_nh_event_provider(
ProviderId int,
ProviderName nvarchar(255),
ProviderClassName nvarchar(255),
AssemblyName nvarchar(260),
SystemName nvarchar(255),
StartTime datetime,
Interval int,
Timeout int,
ActivationState tinyint
)
INSERT #tmp_nh_event_provider EXEC [SchemaPrefix].NSGetProviders 'NonHostedOnly'
DROP TABLE #tmp_nh_event_provider
nhep.ProviderNamenhep.ProviderIdnhep.ActivationState
CREATE TABLE #tmp_event_chronicle_rule(
RuleId int,
RuleName nvarchar(255),
RuleType tinyint,
Action ntext,
ActionTimeout int,
EventClassId int,
SubscriptionClassId int,
EventClassName nvarchar(255),
InputTypeName nvarchar (128),
InputTypeSchema nvarchar (128),
SqlUserName nvarchar (128),
SqlLoginName nvarchar (128)
)
INSERT #tmp_event_chronicle_rule EXEC [SchemaPrefix].NSGetRulesOnType @RuleType = 0
DROP TABLE #tmp_event_chronicle_rule
ecr.RuleIdecr.RuleNameecr.SubscriptionClassIdecr.Actionecr.ActionTimeoutecr.EventClassId
r
CREATE TABLE #tmp_event_chronicle(
EventChronicleId int,
ChronicleName nvarchar(255),
EventClassId int,
SqlStatementsXml nvarchar(max)
)
INSERT #tmp_event_chronicle EXEC [SchemaPrefix].NSGetEventChronicles
DROP TABLE #tmp_event_chronicle
echn.ChronicleNameechn.EventChronicleIdechn.EventClassIdnullechn.SqlStatementsXml
CREATE TABLE #tmp_event_class(
EventClassId int,
EventClassName nvarchar(255),
FileGroup nvarchar(128),
IndexSqlStatementsXml nvarchar(max),
RuleId int,
RuleName nvarchar(255),
RuleType tinyint,
Action ntext,
ActionTimeout int
)
INSERT #tmp_event_class EXEC [SchemaPrefix].NSGetEventClassesWithSqlStatements
DROP TABLE #tmp_event_class
evt.EventClassNameevt.FileGroupevt.EventClassIdnullevt.IndexSqlStatementsXmlevt.RuleIdevt.RuleNameevt.RuleTypeevt.Actionevt.ActionTimeout
CREATE TABLE #tmp_distributors(
DistributorId int,
DistributorName nvarchar(255),
SystemName nvarchar(255),
ThreadPoolSize int,
QuantumDuration int,
ActivationState tinyint
)
INSERT #tmp_distributors EXEC [SchemaPrefix].NSGetDistributors
DROP TABLE #tmp_distributors
dds.DistributorNamedds.DistributorIddds.SystemNamedds.ThreadPoolSizedds.QuantumDurationdds.ActivationState
n
CREATE TABLE #tmp_vacuum_schedule(
VacuumScheduleId int,
StartTime datetime,
Interval int
)
INSERT #tmp_vacuum_schedule EXEC [SchemaPrefix].NSGetVacuumSchedule
DROP TABLE #tmp_vacuum_schedule
dvs.VacuumScheduleIddvs.VacuumScheduleIddvs.StartTimedvs.Interval
,
CREATE TABLE #tmp_application_names(
ApplicationName nvarchar(max),
ApplicationDb nvarchar(128),
AppSchemaName nvarchar (128),
DropOnDelete bit,
ApplicationEnabled bit,
SubscribersEnabled bit,
SubscriptionsEnabled bit,
EventProviderEnabled bit,
GeneratorEnabled bit,
DistributorEnabled bit,
)
INSERT #tmp_application_names EXEC [SchemaPrefix].NSGetApplicationNames
CREATE TABLE #tmp_local_application_details(
ApplicationName nvarchar(max),
BaseDirectoryPath nvarchar(260),
ApplicationDefinitionFilePath nvarchar(260),
QuantumDuration int,
ChronicleQuantumLimit int,
SubscriptionQuantumLimit int,
ProcessEventsInOrder bit,
RetentionAge int,
PerformanceQueryInterval int,
EventThrottle int,
SubscriptionThrottle int,
NotificationThrottle int,
LogBeforeDeliveryAttempts bit,
LogStatusInfo bit,
LogNotificationText bit,
)
CREATE TABLE #tmp_application_version(
ApplicationName nvarchar(max),
ApplicationDatabase nvarchar (255),
SchemaName nvarchar (255),
VersionId int,
UpdateDescription nvarchar(255),
UpdateStarted datetime,
UpdateFinished datetime,
UpdateUserId nvarchar(255),
NSEdition nvarchar(255),
NSVersionMajor int,
NSVersionMinor int,
NSVersionBuild int,
NSVersionRevision int,
ConfigVersionMajor int,
ConfigVersionMinor int,
ConfigVersionBuild int,
ConfigVersionRevision int,
AdfVersionMajor int,
AdfVersionMinor int,
AdfVersionBuild int,
AdfVersionRevision int
)
CREATE TABLE #tmp_generator_details(
ApplicationName nvarchar(max),
GeneratorId int,
GeneratorName nvarchar(255),
SystemName nvarchar(255),
PreviousFiringTime datetime,
ThreadPoolSize int,
ActivationState tinyint
)
DECLARE @dbname7 sysname
DECLARE @AppSchemaName nvarchar(128)
DECLARE @sql7 NVARCHAR(MAX)
DECLARE applications_cursor CURSOR FOR
SELECT ApplicationDb, AppSchemaName FROM #tmp_application_names FOR READ ONLY
OPEN applications_cursor
FETCH applications_cursor into @dbname7, @AppSchemaName
WHILE @@FETCH_STATUS >= 0
BEGIN
SET @sql7 = CONVERT (NVARCHAR (MAX), N' USE ' + quotename(@dbname7))
SET @sql7 = @sql7 + CONVERT (NVARCHAR (MAX), N' INSERT #tmp_local_application_details EXEC ' + quotename (@AppSchemaName) + N'.NSGetApplicationConfig')
SET @sql7 = @sql7 + CONVERT (NVARCHAR (MAX), N' INSERT #tmp_application_version EXEC ' + quotename (@AppSchemaName) + N'.NSGetVersionInfo')
SET @sql7 = @sql7 + CONVERT (NVARCHAR (MAX), N' INSERT #tmp_generator_details EXEC ' + quotename (@AppSchemaName) + N'.NSGetGenerators')
EXEC (@sql7)
FETCH applications_cursor into @dbname7, @AppSchemaName
END
CLOSE applications_cursor
DEALLOCATE applications_cursor
CREATE TABLE #tmp_application_details(
applicationdb nvarchar(max),
name nvarchar(max),
AppSchemaName nvarchar(128),
ApplicationEnabled bit,
SubscribersEnabled bit,
SubscriptionsEnabled bit,
EventProviderEnabled bit,
GeneratorEnabled bit,
DistributorEnabled bit,
BaseDirectoryPath nvarchar(260),
ApplicationDefinitionFilePath nvarchar(260),
QuantumDuration int,
ChronicleQuantumLimit int,
SubscriptionQuantumLimit int,
ProcessEventsInOrder bit,
RetentionAge int,
PerformanceQueryInterval int,
EventThrottle int,
SubscriptionThrottle int,
NotificationThrottle int,
LogBeforeDeliveryAttempts bit,
LogStatusInfo bit,
LogNotificationText bit,
NSVersionMajor int,
NSVersionMinor int,
NSVersionBuild int,
NSVersionRevision int,
AdfVersionMajor int,
AdfVersionMinor int,
AdfVersionBuild int,
AdfVersionRevision int,
GeneratorId int,
GeneratorName nvarchar(255)
)
DECLARE @ApplicationName nvarchar (128)
DECLARE application_details_cursor CURSOR FOR
SELECT ApplicationName, ApplicationDb FROM #tmp_application_names
FOR READ ONLY
OPEN application_details_cursor
FETCH application_details_cursor into @ApplicationName, @dbname7
WHILE @@FETCH_STATUS >= 0
BEGIN
SET @sql7 = CONVERT (NVARCHAR (MAX), N' USE ' + quotename(@dbname7))
SET @sql7 = @sql7 + CONVERT (NVARCHAR (MAX), N' INSERT #tmp_application_details')
SET @sql7 = @sql7 + CONVERT (NVARCHAR (MAX), N' SELECT app.ApplicationDb, app.ApplicationName, app.AppSchemaName, ')
SET @sql7 = @sql7 + CONVERT (NVARCHAR (MAX), N' app.ApplicationEnabled, app.SubscribersEnabled, app.SubscriptionsEnabled,')
SET @sql7 = @sql7 + CONVERT (NVARCHAR (MAX), N' app.EventProviderEnabled, app.GeneratorEnabled, app.DistributorEnabled,')
SET @sql7 = @sql7 + CONVERT (NVARCHAR (MAX), N' cfg.BaseDirectoryPath, cfg.ApplicationDefinitionFilePath,')
SET @sql7 = @sql7 + CONVERT (NVARCHAR (MAX), N' cfg.QuantumDuration, cfg.ChronicleQuantumLimit, cfg.SubscriptionQuantumLimit,')
SET @sql7 = @sql7 + CONVERT (NVARCHAR (MAX), N' cfg.ProcessEventsInOrder, cfg.RetentionAge, cfg.PerformanceQueryInterval, cfg.EventThrottle, cfg.SubscriptionThrottle,')
SET @sql7 = @sql7 + CONVERT (NVARCHAR (MAX), N' cfg.NotificationThrottle, cfg.LogBeforeDeliveryAttempts, cfg.LogStatusInfo, cfg.LogNotificationText, ')
SET @sql7 = @sql7 + CONVERT (NVARCHAR (MAX), N' ver.NSVersionMajor, ver.NSVersionMinor, ver.NSVersionBuild, ver.NSVersionRevision,')
SET @sql7 = @sql7 + CONVERT (NVARCHAR (MAX), N' ver.AdfVersionMajor, ver.AdfVersionMinor, ver.AdfVersionBuild, ver.AdfVersionRevision,')
SET @sql7 = @sql7 + CONVERT (NVARCHAR (MAX), N' gen.GeneratorId, gen.GeneratorName')
SET @sql7 = @sql7 + CONVERT (NVARCHAR (MAX), N' FROM #tmp_local_application_details as cfg, #tmp_application_version as ver, #tmp_generator_details as gen, #tmp_application_names as app')
SET @sql7 = @sql7 + CONVERT (NVARCHAR (MAX), N' WHERE app.ApplicationName = N' + quotename (@ApplicationName, N''''))
SET @sql7 = @sql7 + CONVERT (NVARCHAR (MAX), N' AND cfg.ApplicationName = N' + quotename (@ApplicationName, N''''))
SET @sql7 = @sql7 + CONVERT (NVARCHAR (MAX), N' AND ver.ApplicationName = N' + quotename (@ApplicationName, N''''))
SET @sql7 = @sql7 + CONVERT (NVARCHAR (MAX), N' AND gen.ApplicationName = N' + quotename (@ApplicationName, N''''))
EXEC (@sql7)
FETCH application_details_cursor into @ApplicationName, @dbname7
END
CLOSE application_details_cursor
DEALLOCATE application_details_cursor
DROP TABLE #tmp_application_details
DROP TABLE #tmp_generator_details
DROP TABLE #tmp_application_version
DROP TABLE #tmp_local_application_details
DROP TABLE #tmp_application_names
dad.namedad.applicationdbdad.AppSchemaNamedad.applicationdbdad.InstanceNamenulldad.NSVersionMajordad.NSVersionMinordad.NSVersionBuilddad.NSVersionRevisionnulldad.AdfVersionMajordad.AdfVersionMinordad.AdfVersionBuilddad.AdfVersionRevisiondad.BaseDirectoryPathdad.ApplicationDefinitionFilePathdad.QuantumDurationdad.ChronicleQuantumLimitdad.SubscriptionQuantumLimitdad.ProcessEventsInOrderdad.PerformanceQueryIntervaldad.EventThrottledad.SubscriptionThrottledad.NotificationThrottledad.LogBeforeDeliveryAttemptsdad.LogStatusInfodad.LogNotificationTextdad.RetentionAgedad.ApplicationEnableddad.SubscribersEnableddad.SubscriptionsEnableddad.EventProviderEnableddad.GeneratorEnableddad.DistributorEnableddad.GeneratorIddad.GeneratorName
:
CREATE TABLE #tmp_InstLogFiles (
LogicalName nvarchar(128),
FilePath nvarchar(260),
FileGroupName nvarchar(128),
InitialSize nvarchar(32),
MaxSize nvarchar(32),
GrowthIncrement nvarchar(16)
)
INSERT INTO #tmp_InstLogFiles EXEC [SchemaPrefix].NSGetDatabaseFiles 'LOG_ONLY'
DROP TABLE #tmp_InstLogFiles
ilf.LogicalNameilf.FilePathilf.InitialSizeilf.MaxSizeilf.GrowthIncrement
CREATE TABLE #tmp_InstDatabaseFiles (
LogicalName nvarchar(128),
FilePath nvarchar(260),
FileGroupName nvarchar(128),
InitialSize nvarchar(32),
MaxSize nvarchar(32),
GrowthIncrement nvarchar(16)
)
INSERT INTO #tmp_InstDatabaseFiles EXEC [SchemaPrefix].NSGetDatabaseFiles 'DATA_ONLY'
DROP TABLE #tmp_InstDatabaseFiles
idf.LogicalNameidf.FilePathidf.FileGroupNameidf.InitialSizeidf.MaxSizeidf.GrowthIncrement
CREATE TABLE #tmp_InstDatabaseFiles1 (
LogicalName nvarchar(128),
FilePath nvarchar(260),
FileGroupName nvarchar(128),
InitialSize nvarchar(32),
MaxSize nvarchar(32),
GrowthIncrement nvarchar(16)
)
CREATE TABLE #tmp_InstanceDatabaseFileGroups (
FileGroupName nvarchar(128)
)
INSERT INTO #tmp_InstDatabaseFiles1 EXEC [SchemaPrefix].NSGetDatabaseFiles 'DATA_ONLY'
INSERT INTO #tmp_InstanceDatabaseFileGroups SELECT DISTINCT FileGroupName FROM #tmp_InstDatabaseFiles1
DROP TABLE #tmp_InstanceDatabaseFileGroups
DROP TABLE #tmp_InstDatabaseFiles1
idfg.FileGroupName
i
CREATE TABLE #tmp_InstDatabaseOptions (
SystemName nvarchar(255),
DefaultFileGroup nvarchar(128),
CollationName nvarchar(255)
)
INSERT INTO #tmp_InstDatabaseOptions EXEC [SchemaPrefix].NSGetDatabaseOptions
DROP TABLE #tmp_InstDatabaseOptions
ido.SystemNameido.DefaultFileGroupido.CollationName
1
CREATE TABLE #tmp_AppLogFiles (
LogicalName nvarchar(128),
FilePath nvarchar(260),
FileGroupName nvarchar(128),
InitialSize nvarchar(32),
MaxSize nvarchar(32),
GrowthIncrement nvarchar(16)
)
INSERT INTO #tmp_AppLogFiles EXEC [SchemaPrefix].NSGetDatabaseFiles 'LOG_ONLY'
DROP TABLE #tmp_AppLogFiles
alf.LogicalNamealf.FilePathalf.InitialSizealf.MaxSizealf.GrowthIncrement
CREATE TABLE #tmp_AppDatabaseFiles (
LogicalName nvarchar(128),
FilePath nvarchar(260),
FileGroupName nvarchar(128),
InitialSize nvarchar(32),
MaxSize nvarchar(32),
GrowthIncrement nvarchar(16)
)
INSERT INTO #tmp_AppDatabaseFiles EXEC [SchemaPrefix].NSGetDatabaseFiles 'DATA_ONLY'
DROP TABLE #tmp_AppDatabaseFiles
adf.LogicalNameadf.FilePathadf.FileGroupNameadf.InitialSizeadf.MaxSizeadf.GrowthIncrement
CREATE TABLE #tmp_AppDatabaseFiles1 (
LogicalName nvarchar(128),
FilePath nvarchar(260),
FileGroupName nvarchar(128),
InitialSize nvarchar(32),
MaxSize nvarchar(32),
GrowthIncrement nvarchar(16)
)
CREATE TABLE #tmp_ApplicationDatabaseFileGroups (
FileGroupName nvarchar(128)
)
INSERT INTO #tmp_AppDatabaseFiles1 EXEC [SchemaPrefix].NSGetDatabaseFiles 'DATA_ONLY'
INSERT INTO #tmp_ApplicationDatabaseFileGroups SELECT DISTINCT FileGroupName FROM #tmp_AppDatabaseFiles1
DROP TABLE #tmp_ApplicationDatabaseFileGroups
DROP TABLE #tmp_AppDatabaseFiles1
adfg.FileGroupName
`
CREATE TABLE #tmp_AppDatabaseOptions (
SystemName nvarchar(255),
DefaultFileGroup nvarchar(128),
CollationName nvarchar(255)
)
INSERT INTO #tmp_AppDatabaseOptions EXEC [SchemaPrefix].NSGetDatabaseOptions
DROP TABLE #tmp_AppDatabaseOptions
ado.SystemNameado.DefaultFileGroupado.CollationName
CREATE TABLE #tmp_generators(
ApplicationName nvarchar(max),
GeneratorId int,
GeneratorName nvarchar(255),
SystemName nvarchar(255),
PreviousFiringTime datetime,
ThreadPoolSize int,
ActivationState tinyint
)
INSERT #tmp_generators EXEC [SchemaPrefix].NSGetGenerators
DROP TABLE #tmp_generators
gen.GeneratorNamegen.GeneratorIdgen.SystemNamegen.PreviousFiringTimegen.ThreadPoolSizegen.ActivationState
s
CREATE TABLE #tmp_protocol_definitions(
ProtocolName nvarchar(255),
ClassName nvarchar(255),
AssemblyName nvarchar(260)
)
INSERT #tmp_protocol_definitions EXEC [SchemaPrefix].NSGetProtocols 0
DROP TABLE #tmp_protocol_definitions
dpd.ProtocolNamedpd.ClassNamedpd.AssemblyName
t
CREATE TABLE #tmp_delivery_channels_args(
DeliveryChannelName nvarchar(255),
ArgumentName nvarchar(255),
ArgumentValue nvarchar(4000)
)
INSERT #tmp_delivery_channels_args EXEC [SchemaPrefix].NSGetDeliveryChannelArguments
DROP TABLE #tmp_delivery_channels_args
dcab.ArgumentNamedcab.ArgumentValuedcab.DeliveryChannelName
CREATE TABLE #tmp_delivery_channels(
DeliveryChannelName nvarchar(255),
ProtocolName nvarchar(255)
)
INSERT #tmp_delivery_channels EXEC [SchemaPrefix].NSGetDeliveryChannels
DROP TABLE #tmp_delivery_channels
dcb.DeliveryChannelNamedcb.ProtocolName
CREATE TABLE #tmp_instance_db_names (
Name nvarchar(64),
InstanceDatabase nvarchar (255),
SchemaName nvarchar (255),
VersionId int,
UpdateDescription nvarchar (255),
UpdateStarted datetime,
UpdateFinished datetime,
UpdateUserId nvarchar (255),
NSEdition nvarchar(255),
NSVersionMajor int,
NSVersionMinor int,
NSVersionBuild int,
NSVersionRevision int,
ConfigVersionMajor int,
ConfigVersionMinor int,
ConfigVersionBuild int,
ConfigVersionRevision int,
AdfVersionMajor int,
AdfVersionMinor int,
AdfVersionBuild int,
AdfVersionRevision int,
EncryptArguments bit
)
CREATE TABLE #tmp_instance_info (
Name nvarchar(64),
InstanceDatabase nvarchar (255),
SchemaName nvarchar (255),
VersionId int,
UpdateDescription nvarchar (255),
UpdateStarted datetime,
UpdateFinished datetime,
UpdateUserId nvarchar (255),
NSEdition nvarchar(255),
NSVersionMajor int,
NSVersionMinor int,
NSVersionBuild int,
NSVersionRevision int,
ConfigVersionMajor int,
ConfigVersionMinor int,
ConfigVersionBuild int,
ConfigVersionRevision int,
AdfVersionMajor int,
AdfVersionMinor int,
AdfVersionBuild int,
AdfVersionRevision int
)
CREATE TABLE #tmp_instance_encryption (
Name nvarchar(64),
EncryptArguments bit
)
IF OBJECT_ID(N'msdb.NS90.NSInstances') IS NOT NULL
BEGIN
DECLARE @dbname NVARCHAR (255)
DECLARE @SchemaName NVARCHAR (255)
DECLARE @sql NVARCHAR(MAX)
DECLARE instance_db_names_cursor CURSOR FOR
SELECT DatabaseName, SchemaName FROM [msdb].[NS90].[NSInstances]
FOR READ ONLY
OPEN instance_db_names_cursor
FETCH instance_db_names_cursor into @dbname, @SchemaName
WHILE @@FETCH_STATUS >= 0
BEGIN
SET @sql = CONVERT (NVARCHAR (MAX), N' USE ' + quotename(@dbname))
SET @sql = @sql + CONVERT (NVARCHAR (MAX), N' IF OBJECT_ID(N' + quotename (quotename (@SchemaName) + N'.NSGetVersionInfo', N'''') + N') IS NOT NULL')
SET @sql = @sql + CONVERT (NVARCHAR (MAX), N' BEGIN')
SET @sql = @sql + CONVERT (NVARCHAR (MAX), N' IF EXISTS (SELECT * FROM sys.columns AS Columns WHERE Columns.object_id = OBJECT_ID (N' + quotename (quotename (@SchemaName) + N'.NSInstanceConfig', N'''') + N') AND Columns.name = ''EncryptArguments'')')
SET @sql = @sql + CONVERT (NVARCHAR (MAX), N' BEGIN')
SET @sql = @sql + CONVERT (NVARCHAR (MAX), N' INSERT #tmp_instance_info')
SET @sql = @sql + CONVERT (NVARCHAR (MAX), N' EXEC ' + quotename (@SchemaName) + N'.NSGetVersionInfo')
SET @sql = @sql + CONVERT (NVARCHAR (MAX), N' INSERT #tmp_instance_encryption')
SET @sql = @sql + CONVERT (NVARCHAR (MAX), N' EXEC ' + quotename (@SchemaName) + N'.NSGetInstanceConfig')
SET @sql = @sql + CONVERT (NVARCHAR (MAX), N' END')
SET @sql = @sql + CONVERT (NVARCHAR (MAX), N' END')
EXEC (@sql)
FETCH instance_db_names_cursor into @dbname, @SchemaName
END
INSERT INTO #tmp_instance_db_names
SELECT
Info.Name, Info.InstanceDatabase, Info.SchemaName, Info.VersionId,
Info.UpdateDescription, Info.UpdateStarted, Info.UpdateFinished, Info.UpdateUserId,
Info.NSEdition, Info.NSVersionMajor, Info.NSVersionMinor, Info.NSVersionBuild, Info.NSVersionRevision,
Info.ConfigVersionMajor, Info.ConfigVersionMinor, Info.ConfigVersionBuild, Info.ConfigVersionRevision,
Info.AdfVersionMajor, Info.AdfVersionMinor, Info.AdfVersionBuild, Info.AdfVersionRevision,
Config.EncryptArguments
FROM #tmp_instance_info AS Info, #tmp_instance_encryption AS Config
WHERE Info.Name = Config.Name
CLOSE instance_db_names_cursor
DEALLOCATE instance_db_names_cursor
END
DROP TABLE #tmp_instance_encryption
DROP TABLE #tmp_instance_info
DROP TABLE #tmp_instance_db_names
dtb.Namedtb.InstanceDatabasedtb.SchemaNamenulldtb.NSVersionMajordtb.NSVersionMinordtb.NSVersionBuilddtb.NSVersionRevisionnulldtb.ConfigVersionMajordtb.ConfigVersionMinordtb.ConfigVersionBuilddtb.ConfigVersionRevisiondtb.EncryptArgumentsserverproperty(N'Servername')ke.key_idke.thumbprintISNULL(ke.thumbprint, 0x00)(case ke.crypt_type
when 'ESKS' then 0 when 'EPUC' then 1 when 'ESKP' then 2 when 'EPUA' then 3 when 'ESKM' then 4 else -1 end)(case ke.crypt_type
when 'ESKS' then 0 when 'EPUC' then 1 when 'ESKP' then 2 when 'EPUA' then 3 when 'ESKM' then 4 else -1 end)ke.crypt_propertyc.symmetric_key_id = 101ok.key_id=c.symmetric_key_id and ok.database_id=db_id()mkdb.database_id=db_id()c.symmetric_key_idc.create_datec.modify_dateISNULL(ok.status, 0)ISNULL(mkdb.is_master_key_encrypted_by_server, 0)
~
<
@account_name is not null
declare @SysAdminOnly int
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'SysAdminOnly', @SysAdminOnly OUTPUT
set @SysAdminOnly = (case when 0 = @SysAdminOnly then 1 else 0 end)
create table #tmpProxyAccountName ( domain sysname, username sysname)
insert into #tmpProxyAccountName exec master.dbo.xp_sqlagent_proxy_account N'GET'
declare @account_name nvarchar(255)
set @account_name = (select domain + N'\' + username as [UserName] from #tmpProxyAccountName)
if (@account_name is null)
begin
set @account_name=N''
end
drop table #tmpProxyAccountName
@account_name is not null
declare @SysAdminOnly int
set @SysAdminOnly = (select count(*) from sys.credentials c where c.name = N'##xp_cmdshell_proxy_account##')
declare @account_name nvarchar(4000)
set @account_name = (select top 1 credential_identity from sys.credentials c where c.name = N'##xp_cmdshell_proxy_account##')
if (@account_name is null)
begin
set @account_name=N''
end
@SysAdminOnly@account_name
create table #tmp_sp_help_category
(category_id int null, category_type tinyint null, name nvarchar(128) null)
insert into #tmp_sp_help_category (category_id, category_type, name) exec msdb.dbo.sp_help_category 'OPERATOR'
drop table #tmp_sp_help_category
tshc.nametshc.category_id
}
dt.transaction_id = ts.transaction_idtsnp.transaction_id = ts.transaction_idta.transaction_id = ts.transaction_idta.namets.transaction_idta.transaction_begin_timets.session_iddb_name(dt.database_id)dt.database_iddt.database_transaction_begin_timecase when tsnp.transaction_id is null then 0 else 1 enddt.transaction_id = tsnp.transaction_idta.transaction_id = tsnp.transaction_idta.nametsnp.transaction_idta.transaction_begin_timetsnp.session_iddb_name(dt.database_id)dt.database_iddt.database_transaction_begin_time1
B
create table #tmp_sp_help_category
(category_id int null, category_type tinyint null, name nvarchar(128) null)
insert into #tmp_sp_help_category (category_id, category_type, name) exec msdb.dbo.sp_help_category 'JOB'
drop table #tmp_sp_help_category
tshc.nametshc.category_idtshc.category_type
create table #tmp_sp_help_category
(category_id int null, category_type tinyint null, name nvarchar(128) null)
insert into #tmp_sp_help_category (category_id, category_type, name) exec msdb.dbo.sp_help_category 'ALERT'
drop table #tmp_sp_help_category
tshc.nametshc.category_id
i
ke.thumbprint(case ke.crypt_type when 'ESKS' then 0 when 'EPUC' then 1 when 'ESKP' then 2 when 'EPUA' then 3 when 'ESKM' then 4 end)ke.crypt_propertyke.key_id((s.type = 4) AND (s.drop_lsn IS NULL))CASE param.isoutparam WHEN 1 THEN param.isoutparam WHEN 0 THEN CASE param.name WHEN '' THEN 1 ELSE 0 END ENDparam.numberparam.is_outputparam.procedure_numbernsp.colid = 1 and nsp.number > 1nsp.numberobject_name(nsp.id) + ';' + cast(nsp.number as nvarchar(20))nsp.encryptedcast(nsp.id as nvarchar(20)) + N'_' + cast(db_id() as nvarchar(20)) + N'_' + cast(nsp.number as nvarchar(20))nsp.numbernsp.idnsp.procedure_numberobject_name(nsp.object_id) + ';' + cast(nsp.procedure_number as nvarchar(20))CASE WHEN nsp.definition IS NULL THEN 1 ELSE 0 ENDnsp.definitionnsp.procedure_numbernsp.object_id0
o
clmns.number = 0 and 0 = OBJECTPROPERTY(clmns.id, N'IsScalarFunction')
"
param.nameparam.colidparam.idN'PARAMETER'param.parameter_idparam.object_id2nulldb_name()
)
tbl.name like '#%'
use tempdb
sp.principal_id = a.principal_ida.namea.asymmetric_key_iduser_name(a.principal_id)(case a.algorithm when '1R' then 0 when '2R' then 1 when '2R' then 3 end)a.key_lengthcase a.pvt_key_encryption_type when 'NA' then 0 when 'MK' then 1 when 'PW' then 2 enda.public_keya.sida.thumbprint260c.symmetric_key_id <> 101ok.key_id=c.symmetric_key_id and ok.database_id=db_id()c.namec.symmetric_key_iduser_name(c.principal_id)c.create_datec.key_guidc.key_length(case c.key_algorithm when 'R2' then 0 when 'R4' then 1 when 'D' then 2 when 'D3' then 3 when 'DX' then 4 when 'A1' then 5 when 'A2' then 6 when 'A3' then 7 end)c.modify_dateISNULL(ok.status, 0)240
]
ewm.method_aliasISNULL(ewm.namespace,'')ewm.result_formatewm.object_nameewm.result_schemaewm.endpoint_idcase upper(se.login_type) when 'WINDOWS' then 2 else 1 endte.portte.is_dynamic_portISNULL(te.ip_address,'')te.endpoint_id
w
ISNULL(he.authorization_realm,N'')he.clear_portISNULL(he.default_logon_domain,N'')1*he.is_ssl_port_enabled + 2*is_clear_port_enabledhe.ssl_porthe.url_pathhe.sitehe.is_compression_enabled1*is_anonymous_enabled + 2*is_basic_auth_enabled + 4*is_digest_auth_enabled + 8*is_integrated_auth_enabledhe.endpoint_idve.discriminatorve.endpoint_idcert.certificate_id = sbe.certificate_idsbe.is_message_forwarding_enabledsbe.message_forwarding_sizeISNULL(cert.name,N'')
case
when sbe.encryption_algorithm = 0 then 0
when sbe.encryption_algorithm in (3,4,7,8) then 1
when sbe.encryption_algorithm in (1,2,5,6) then 2
else 0
end
case sbe.encryption_algorithm
when 0 then 0
when 1 then 1
when 2 then 2
when 3 then 1
when 4 then 2
when 5 then 4
when 6 then 3
when 7 then 4
when 8 then 3
else 0
end
sbe.connection_authsbe.endpoint_idcert.certificate_id = dme.certificate_iddme.roleISNULL(cert.name,N'')case
when dme.encryption_algorithm = 0 then 0
when dme.encryption_algorithm in (3,4,7,8) then 1
when dme.encryption_algorithm in (1,2,5,6) then 2
else 0
end
case dme.encryption_algorithm
when 0 then 0
when 1 then 1
when 2 then 2
when 3 then 1
when 4 then 2
when 5 then 4
when 6 then 3
when 7 then 4
when 8 then 3
else 0
end
dme.connection_authdme.endpoint_idISNULL(se.default_database, N'')se.is_sql_language_enabledse.default_namespace2-convert(int, se.is_xml_charset_enforced)se.default_result_schemase.wsdl_generator_procedurecase LEN(ISNULL(se.wsdl_generator_procedure,'')) when 0 then 0 else 2 endse.is_session_enabledse.session_timeoutCASE WHEN se.session_timeout < 0 THEN 1 ELSE 0 ENDse.endpoint_id
6
sp.principal_id = e.principal_ide.namee.endpoint_idsp.namee.typee.protocole.statee.is_admin_endpoint105
drop table #account_server_tmp
ast.servernameast.portISNULL(ast.username, N'')ast.nameast.servertypeast.use_default_credentialsast.enable_ssl
drop table #principal_profile_tmp
ppt.principal_nameppt.principal_idppt.profile_nameppt.profile_idppt.is_default
drop table #profile_account_tmp
pat.profile_namepat.profile_idpat.account_namepat.account_idpat.sequence_numberte.typete.type_desccast(db_id() as varchar(20)) + '_' + cast(te.object_id as varchar(20))te.object_id
B
nullte.typete.type_desccast(db_id() as varchar(20)) + '_' + cast(te.object_id as varchar(20))te.object_id
b
sm{0}.object_id = {0}.object_idssm{0}.object_id = {0}.object_idISNULL(sm{0}.uses_ansi_nulls, ssm{0}.uses_ansi_nulls)ISNULL(sm{0}.uses_quoted_identifier, ssm{0}.uses_quoted_identifier)OBJECTPROPERTYEX({0}.object_id, N'IsSchemaBound')tr.parent_class = 100mod.object_id = tr.object_idam2tr.object_id = tr.object_idssmod.object_id = tr.object_idasmbl.assembly_id = mod.assembly_id~tr.is_disabledCASE WHEN tr.type = N'TR' THEN N'' ELSE asmbl.name ENDCASE WHEN tr.type = N'TR' THEN N'' ELSE mod.assembly_class ENDCASE WHEN tr.type = N'TR' THEN N'' ELSE mod.assembly_method ENDCASE WHEN tr.type = N'TR' THEN 1 WHEN tr.type = N'TA' THEN 2 ELSE 1 ENDssmod.uses_ansi_nullsssmod.uses_quoted_identifierssmod.definitionISNULL(user_name(ssmod.execute_as_principal_id),ISNULL(user_name(mod.execute_as_principal_id),N''))CASE WHEN (ssmod.execute_as_principal_id IS NULL AND mod.execute_as_principal_id IS NULL) THEN 1 ELSE 2 ENDNULLNULLCASE WHEN ssmod.definition IS NULL THEN 1 ELSE 0 ENDnulltr.parent_class = 0am2tr.object_id = tr.object_idsqlmod.object_id = tr.object_idtr.is_not_for_replication~tr.is_disabledCASE WHEN tr.type = N'TR' THEN 1 WHEN tr.type = N'TA' THEN 2 ELSE 1 ENDsqlmod.uses_ansi_nullssqlmod.uses_quoted_identifier{0}.name{0}.id{0}.crdate{0}.parent_obj{0}.name{0}.object_id{0}.create_date{0}.modify_date{0}.parent_object_id10
m
{
create table #tmp_sysmail_help_configure(paramname nvarchar(256), paramvalue nvarchar(256) null, description nvarchar(256) null)
insert into #tmp_sysmail_help_configure(paramname, paramvalue, description) exec msdb.dbo.sysmail_help_configure_sp
drop table #tmp_sysmail_help_configure
tshc.paramnametshc.paramvaluetshc.description
create table #tmp_sysmail_help_account(account_id int, name nvarchar(128), description nvarchar(256) null, email_address nvarchar(128) null, display_name nvarchar(128) null, replyto_address nvarchar(128) null, servertype nvarchar(128), servername nvarchar(128), port int, username nvarchar(128), use_default_credentials bit, enable_ssl bit)
insert into #tmp_sysmail_help_account(account_id, name, description, email_address, display_name, replyto_address, servertype, servername, port, username, use_default_credentials, enable_ssl) exec msdb.dbo.sysmail_help_account_sp
drop table #tmp_sysmail_help_account
tsha.nametsha.account_idISNULL(tsha.description, N'')tsha.email_addressISNULL(tsha.display_name, N'')ISNULL(tsha.replyto_address, N'')
+
create table #tmp_sysmail_help_profile(profile_id int, name nvarchar(128), description nvarchar(256) null)
insert into #tmp_sysmail_help_profile(profile_id, name, description) exec msdb.dbo.sysmail_help_profile_sp
drop table #tmp_sysmail_help_profile
tshp.nametshp.profile_idISNULL(tshp.description,N'')
)
s.names.credential_ids.credential_identitys.create_dates.modify_datecomp.namecomp.xml_component_idcomp.xml_namespace_idcomp.is_qualified(case comp.kind
when 'N' then 1
when 'Z' then 2
when 'P' then 3
when 'S' then 4
when 'L' then 5
when 'U' then 6
when 'C' then 7
when 'K' then 8
when 'E' then 9
when 'M' then 10
when 'W' then 11
when 'A' then 12
when 'G' then 13
when 'V' then 14
else 1 end) (case comp.derivation when 'N' then 1 when 'X' then 2 when 'R' then 3 when 'S' then 4 else 1 end)comp.base_xml_component_idcomp.scoping_xml_component_idxsc2.xml_collection_id = xn.xml_collection_idxsc.schema_id = sch2.schema_idxn.namexn.xml_namespace_idXML_SCHEMA_NAMESPACE(sch2.Name, xsc2.name, xn.name)xn.xml_collection_id
xsc.schema_id <> 4xsc.schema_id = sch.schema_idxsc.namexsc.xml_collection_idsch.namexsc.create_datexsc.modify_dateXML_SCHEMA_NAMESPACE(sch.Name, xsc.name)10xsc.xml_collection_id0
X
dmw.database_namedmw.principal_server_namedmw.mirror_server_namedmw.safety_leveldmw.safety_sequence_numberdmw.role_sequence_numberdmw.mirroring_guiddmw.family_guiddmw.is_suspendeddmw.is_suspended_sequence_number
create table #err_fulltext_text_tmp(Text nvarchar(4000), ArchiveNo int null, ctlgid int null, LogDate datetime null, ProcessInfo nvarchar(100) null)
declare @text_offset int
declare @process_info_length int
set @text_offset = 34
set @process_info_length = 10
drop table #err_fulltext_text_tmp
ert.LogDateert.ProcessInfoert.Textert.ArchiveNoert.ctlgid
drop table #fulltext_log_tmp
er.ArchiveNoer.ArchiveNoCONVERT(datetime, er.CreateDate, 101)er.Sizeer.ctlgido.provider_name=op.Name
create table #OLEDBProv (id int identity(1,1), Name sysname NOT NULL, ParseName sysname NOT NULL,Description sysname NOT NULL )
insert #OLEDBProv (Name, ParseName,Description) EXECUTE master.dbo.xp_enum_oledb_providers
insert #OLEDBProv (Name, ParseName,Description) EXECUTE master.dbo.sp_enum_oledb_providers
delete from #OLEDBProv where exists ( select 1 from #OLEDBProv oprov where oprov.Name = #OLEDBProv.Name and oprov.id < #OLEDBProv.id )
create table #oledbprop (allow_in_process bit, disallow_adhoc_access bit, dynamic_parameters bit, index_as_access_path bit,
level_zero_only bit, nested_queries bit, non_transacted_updates bit, sql_server_like bit, provider_name sysname null)
declare name_cursor cursor local fast_forward
FOR (select Name from #OLEDBProv)
open name_cursor
DECLARE @providername sysname
FETCH NEXT FROM name_cursor INTO @providername
WHILE (@@FETCH_STATUS <> -1)
BEGIN
IF (@@FETCH_STATUS <> -2)
BEGIN
SELECT @providername = RTRIM(@providername)
declare @regpath nvarchar(255)
set @regpath = N'SOFTWARE\Microsoft\MSSQLServer\Providers\' + @providername
declare @allow_in_process int
declare @disallow_adhoc_access int
declare @dynamic_parameters int
declare @index_as_access_path int
declare @level_zero_only int
declare @nested_queries int
declare @non_transacted_updates int
declare @sql_server_like int
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', @regpath, 'AllowInProcess', @allow_in_process OUTPUT
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', @regpath, 'DisallowAdHocAccess', @disallow_adhoc_access OUTPUT
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', @regpath, 'DynamicParameters', @dynamic_parameters OUTPUT
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', @regpath, 'IndexAsAccessPath', @index_as_access_path OUTPUT
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', @regpath, 'LevelZeroOnly', @level_zero_only OUTPUT
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', @regpath, 'NestedQueries', @nested_queries OUTPUT
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', @regpath, 'NonTransactedUpdates', @non_transacted_updates OUTPUT
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', @regpath, 'SqlServerLIKE', @sql_server_like OUTPUT
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', @regpath, 'AllowInProcess', @allow_in_process OUTPUT
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', @regpath, 'DisallowAdHocAccess', @disallow_adhoc_access OUTPUT
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', @regpath, 'DynamicParameters', @dynamic_parameters OUTPUT
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', @regpath, 'IndexAsAccessPath', @index_as_access_path OUTPUT
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', @regpath, 'LevelZeroOnly', @level_zero_only OUTPUT
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', @regpath, 'NestedQueries', @nested_queries OUTPUT
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', @regpath, 'NonTransactedUpdates', @non_transacted_updates OUTPUT
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', @regpath, 'SqlServerLIKE', @sql_server_like OUTPUT
insert #oledbprop (allow_in_process, disallow_adhoc_access, dynamic_parameters, index_as_access_path, level_zero_only,
nested_queries, non_transacted_updates, sql_server_like, provider_name)
select IsNull(@allow_in_process, 0), IsNull(@disallow_adhoc_access, 0), IsNull(@dynamic_parameters, 0), IsNull(@index_as_access_path, 0), IsNull(@level_zero_only, 0),
IsNull(@nested_queries, 0), IsNull(@non_transacted_updates, 0), IsNull(@sql_server_like, 0), @providername
END
FETCH NEXT FROM name_cursor INTO @providername
END
CLOSE name_cursor
DEALLOCATE name_cursor
create table #oledbprop (allow_in_process bit, disallow_adhoc_access bit, dynamic_parameters bit, index_as_access_path bit,
level_zero_only bit, nested_queries bit, non_transacted_updates bit, sql_server_like bit, provider_name sysname null)
declare name_cursor cursor local fast_forward
FOR (select Name from #OLEDBProv)
open name_cursor
DECLARE @providername sysname
FETCH NEXT FROM name_cursor INTO @providername
WHILE (@@FETCH_STATUS <> -1)
BEGIN
IF (@@FETCH_STATUS <> -2)
BEGIN
SELECT @providername = RTRIM(@providername)
insert #oledbprop (provider_name, allow_in_process, disallow_adhoc_access, dynamic_parameters, index_as_access_path, level_zero_only,
nested_queries, non_transacted_updates, sql_server_like)
exec master.dbo.sp_MSset_oledb_prop @providername
END
FETCH NEXT FROM name_cursor INTO @providername
END
CLOSE name_cursor
DEALLOCATE name_cursor
drop table #oledbprop
drop table #OLEDBProvop.Nameop.Descriptiono.allow_in_processo.disallow_adhoc_accesso.dynamic_parameterso.index_as_access_patho.level_zero_onlyo.nested_querieso.non_transacted_updateso.sql_server_like
w
c.namec.certificate_iduser_name(c.principal_id)case c.pvt_key_encryption_type when 'NA' then 0 when 'MK' then 1 when 'PW' then 2 endc.issuer_namec.cert_serial_numberc.sidc.subjectc.expiry_datec.start_datec.thumbprintc.is_active_for_begin_dialog250
G
create table #tmp_sp_enum_login_for_proxy(proxy_id int null, proxy_name nvarchar(128), flags int null, name nvarchar(128) null, sid varbinary(85) null, principal_id int null )
insert into #tmp_sp_enum_login_for_proxy(proxy_id, proxy_name, flags, name, sid, principal_id) exec msdb.dbo.sp_enum_login_for_proxy
drop table #tmp_sp_enum_login_for_proxy
ProxyAccountPrincipalspl.namespl.flagsspl.proxy_id
\
create table #tmp_sp_enum_sqlagent_subsystems
(subsystem nvarchar(max) null, description nvarchar(max) null, subsystem_dll nvarchar(max) null, agent_exe nvarchar(max) null, start_entry_point nvarchar(max) null, event_entry_point nvarchar(max) null, stop_entry_point nvarchar(max) null, max_worker_threads int null, subsystem_id int null)
create table #tmp_sp_help_proxy_subsystem(subsystem nvarchar(max) null, proxy_id int null, name nvarchar(128) null, credential_identity nvarchar(128) null, enabled tinyint null, description nvarchar(1024) null, user_sid varbinary(40) null, credential_id int null, credential_identity_exists int null)
insert into #tmp_sp_enum_sqlagent_subsystems(subsystem, description, subsystem_dll, agent_exe, start_entry_point, event_entry_point, stop_entry_point, max_worker_threads, subsystem_id)
exec msdb.dbo.sp_enum_sqlagent_subsystems
declare @subsystem nvarchar(max)
declare @login sysname
set @login = suser_sname()
declare crs insensitive cursor
for ( select subsystem from #tmp_sp_enum_sqlagent_subsystems )
for read only
open crs
fetch crs into @subsystem
while @@fetch_status >= 0
begin
if 'TSQL' != @subsystem
begin
insert into #tmp_sp_help_proxy_subsystem(proxy_id, name, credential_identity, enabled, description, user_sid, credential_id, credential_identity_exists)
exec msdb.dbo.sp_help_proxy @subsystem_name = @subsystem, @name = @login
update #tmp_sp_help_proxy_subsystem set subsystem = @subsystem where subsystem is null
end
fetch crs into @subsystem
end
close crs
deallocate crs
drop table #tmp_sp_help_proxy_subsystem
drop table #tmp_sp_enum_sqlagent_subsystems
tsepfs.subsystemtsepfs.proxy_id
F
sc.credential_id = tshp.credential_id
create table #tmp_sp_help_proxy(proxy_id int null, name nvarchar(128) null, credential_identity nvarchar(128) null, enabled tinyint null, description nvarchar(1024) null, user_sid varbinary(40) null, credential_id int null, credential_identity_exists int null)
insert into #tmp_sp_help_proxy(proxy_id, name, credential_identity, enabled, description, user_sid, credential_id, credential_identity_exists) exec msdb.dbo.sp_help_proxy
drop table #tmp_sp_help_proxy
tshp.nametshp.proxy_idtshp.enabledISNULL(tshp.description,N'')tshp.credential_idISNULL(sc.name,N'')ISNULL(tshp.credential_identity,N'')l.database_namel.mark_namel.descriptionl.user_namel.lsnl.mark_times.plan_ids.plan_names.date_createds.owners.max_history_rowss.remote_history_servers.max_remote_history_rowss.log_shippingld.line1ld.line2ld.line3ld.line4ld.line5ld.server_nameld.start_timeld.end_timeld.error_numberld.error_messageld.commandld.succeededld.task_detail_idspl.task_detail_idspl.start_timespl.end_timespl.succeededspl.subplan_id
<
sp.subplan_namesp.subplan_idsp.subplan_descriptionsp.job_idsp.schedule_idsp.plan_ids.names.ids.descriptions.create_dates.owners.version_majors.version_minors.version_builds.version_commentsparam.number = 1CASE param.isoutparam WHEN 1 THEN param.isoutparam WHEN 0 THEN CASE param.name WHEN '' THEN 1 ELSE 0 END ENDparam.is_output1dmi.database_id = dtb.database_iddtb.status & 1dtb.status & 4194304dtb.is_ansi_null_default_ondtb.is_ansi_nulls_ondtb.is_ansi_padding_ondtb.is_ansi_warnings_ondtb.is_arithabort_ondtb.is_auto_close_ondtb.is_auto_create_stats_ondtb.is_auto_shrink_ondtb.is_auto_update_stats_ondtb.is_cursor_close_on_commit_ondtb.is_concat_null_yields_null_ondtb.is_numeric_roundabort_ondtb.is_quoted_identifier_ondtb.is_read_onlydtb.is_recursive_triggers_ondtb.is_local_cursor_defaultdtb.page_verify_optiondtb.recovery_modeldtb.user_accessdtb.snapshot_isolation_statedtb.is_db_chaining_ondtb.is_auto_update_stats_async_ondtb.is_date_correlation_ondtb.is_broker_enableddtb.is_trustworthy_ondtb.is_parameterization_forced(case dmi.mirroring_redo_queue_type when N'UNLIMITED' then 0 else dmi.mirroring_redo_queue end)dmi.mirroring_connection_timeoutDATABASEPROPERTYEX(dtb.name, 'IsAnsiNullDefault')DATABASEPROPERTYEX(dtb.name, 'IsAnsiNullsEnabled')DATABASEPROPERTYEX(dtb.name, 'IsAnsiPaddingEnabled')DATABASEPROPERTYEX(dtb.name, 'IsAnsiWarningsEnabled')DATABASEPROPERTYEX(dtb.name, 'IsArithmeticAbortEnabled')DATABASEPROPERTYEX(dtb.name, 'IsAutoCreateStatistics')DATABASEPROPERTYEX(dtb.name, 'IsAutoUpdateStatistics')DATABASEPROPERTYEX(dtb.name, 'IsCloseCursorsOnCommitEnabled')DATABASEPROPERTYEX(dtb.name, 'IsNullConcat')DATABASEPROPERTYEX(dtb.name, 'IsNumericRoundAbortEnabled')DATABASEPROPERTYEX(dtb.name, 'IsQuotedIdentifiersEnabled')DATABASEPROPERTY(dtb.name, 'IsReadOnly')DATABASEPROPERTYEX(dtb.name, 'IsRecursiveTriggersEnabled')DATABASEPROPERTYEX(dtb.name, 'IsLocalCursorsDefault')CASE WHEN 1=DATABASEPROPERTYEX(dtb.name, 'IsTornPageDetectionEnabled') THEN 1 ELSE 0 ENDCASE DATABASEPROPERTYEX(dtb.name, 'Recovery') WHEN 'SIMPLE' THEN 3 WHEN 'BULK_LOGGED' THEN 2 ELSE /*FULL*/ 1 ENDCASE CONVERT(sysname,DATABASEPROPERTYEX(dtb.name, 'UserAccess')) WHEN 'SINGLE_USER' THEN 1 WHEN 'RESTRICTED_USER' THEN 2 ELSE /*MULTI_USER*/ 0 END1dtb.nameDATABASEPROPERTY(dtb.name, 'IsAnsiNullDefault')DATABASEPROPERTY(dtb.name, 'IsAnsiNullsEnabled')DATABASEPROPERTY(dtb.name, 'IsAnsiWarngingsEnabled')DATABASEPROPERTY(dtb.name, 'IsAutoCreateStatistics')DATABASEPROPERTY(dtb.name, 'IsAutoUpdateStatistics')DATABASEPROPERTY(dtb.name, 'IsCloseCursorsOnCommitEnabled')DATABASEPROPERTY(dtb.name, 'IsQuotedIdentifiersEnabled')DATABASEPROPERTY(dtb.name, 'IsRecursiveTriggersEnabled')DATABASEPROPERTY(dtb.name, 'IsLocalCursorsDefault')
CASE WHEN 1=DATABASEPROPERTY(dtb.name, 'IsTruncLog') THEN CASE WHEN 1=DATABASEPROPERTY(dtb.name, 'IsBulkCopy') THEN NULL ELSE 3/*SIMPLE=trunc. log on chkpt.*/ END
WHEN 1=DATABASEPROPERTY(dtb.name, 'IsBulkCopy') THEN 2 /*BULK_LOGGED*/
ELSE 1 END /*FULL*/
CASE DATABASEPROPERTY(dtb.name, 'IsSingleUser') WHEN 1 THEN 1
ELSE (CASE DATABASEPROPERTY(dtb.name,'IsDboOnly') WHEN 0 THEN 0/*MULTI_USER*/ ELSE 1 END)
END
D
8
DETAILED
6
SAMPLED
@
LIMITED
drop table #contig_tmp
declare @database_id int
select @database_id = db_id()
db_name()nullnullnullnullnullnullnullnullcast(fi.IndexName as varbinary(256))fi.Levelfi.Pagesfi.Rowsfi.MinimumRecordSizefi.MaximumRecordSizefi.AverageRecordSizefi.ForwardedRecordsfi.Extentsfi.ExtentSwitchesfi.AverageFreeBytesfi.AvgPageFullnessfi.ScanDensityfi.BestCountfi.ActualCountfi.LogicalFragmentationfi.ExtentFragmentationfi.index_idfi.object_idfi.index_depthfi.page_countfi.record_countfi.min_record_size_in_bytesfi.max_record_size_in_bytesfi.avg_record_size_in_bytesfi.forwarded_record_countfi.avg_page_space_used_in_percentfi.index_type_descfi.partition_numberfi.ghost_record_countfi.version_ghost_record_countfi.avg_fragmentation_in_percentN''N''N''N''s.base_object_name
5
sms.error > 50000sms.msglangid = sl.lcidsms.message_id > 50000sms.language_id = sl.lcidsms.errorsms.dlevelsms.severitysms.descriptionsms.msglangidsl.namesms.message_idsms.is_event_loggedsms.severitysms.textsms.language_idsl.name
z
sms.error < 50001sms.msglangid = sl.lcidsms.message_id < 50001sms.language_id = sl.lcidsms.errorsms.dlevelsms.severitysms.descriptionsms.msglangidsl.namesms.message_idsms.is_event_loggedsms.severitysms.textsms.language_idsl.namesp.principal_id = prmssn.major_id and prmssn.class = 101nullsp.nameNULLNULLprmssn.major_idc.certificate_id = prmssn.major_id and prmssn.class = 106nullc.nameNULLNULLprmssn.major_ide.endpoint_id = prmssn.major_id and prmssn.class = 105nulle.nameNULLNULLprmssn.major_idobj.object_id = prmssn.major_id and prmssn.class = 1nullobject_name(prmssn.id)user_name(prmssn.uid)nullprmssn.idobj.nameschema_name(obj.schema_id)COL_NAME(prmssn.major_id,prmssn.minor_id)prmssn.major_idobj.schema_id = prmssn.major_id and prmssn.class = 3nullobj.namenullnullprmssn.major_idobj.principal_id = prmssn.major_id and prmssn.class = 4nullobj.namenullnullprmssn.major_idobj.assembly_id = prmssn.major_id and prmssn.class = 5nullobj.namenullnullprmssn.major_idobj.user_type_id = prmssn.major_id and prmssn.class = 6nullobj.namenullnullprmssn.major_idobj.fulltext_catalog_id = prmssn.major_id and prmssn.class = 23nullobj.namenullnullprmssn.major_id
C
null
G
null
(( prmssn.action in (193, 197) and ((prmssn.columns & 1) = 1) ) or ( prmssn.action in (195, 196, 224, 26) ))
and (convert(tinyint, substring( isnull(prmssn.columns, 0x01), a.low, 1)) & a.high != 0)
and a.type = N'P'
and a.number = 0
prmssn.minor_id = 0prmssn.class = 100nullnullnullval1.number = prmssn.protecttype and val1.type = 'T'val2.number = prmssn.action and val2.type = 'T'grantee_principal.uid = prmssn.uidgrantor_principal.uid = prmssn.grantorgrantee_principal.principal_id = prmssn.grantee_principal_idgrantor_principal.principal_id = prmssn.grantor_principal_idgrantee_principal.name + N'_' +
convert(nvarchar(10), (CASE when 1 = grantee_principal.issqlrole THEN 3 WHEN 1 = grantee_principal.isapprole THEN 4 ELSE 2 END)) + N'_' +
grantor_principal.name + N'_' +
convert(nvarchar(10), (CASE when 1 = grantor_principal.issqlrole THEN 3 WHEN 1 = grantor_principal.isapprole THEN 4 ELSE 2 END)) + N'_' +
convert(nvarchar(10), (prmssn.id)) + N'_' +
convert(nvarchar(10), prmssn.protecttype) + N'_' +
convert(nvarchar(10), prmssn.action)
grantee_principal.nameCASE when 1 = grantee_principal.issqlrole THEN 3 WHEN 1 = grantee_principal.isapprole THEN 4 ELSE 2 ENDgrantor_principal.nameCASE when 1 = grantor_principal.issqlrole THEN 3 WHEN 1 = grantor_principal.isapprole THEN 4 ELSE 2 ENDCASE prmssn.id WHEN 0 THEN 0 ELSE 1 END CASE prmssn.protecttype WHEN 204 THEN 87 WHEN 205 THEN 71 WHEN 206 THEN 68 ENDprmssn.protecttypeval1.nameval2.nameCASE prmssn.id WHEN 0 THEN 0 ELSE 1 END prmssn.actionprmssn.idgrantee_principal.name + N'_' +
convert(nvarchar(10), (CASE grantee_principal.type WHEN 'R' THEN 3 WHEN 'A' THEN 4 ELSE 2 END - CASE '{0}' WHEN 'database' THEN 0 ELSE 2 END)) + N'_' +
grantor_principal.name + N'_' +
convert(nvarchar(10), (CASE grantor_principal.type WHEN 'R' THEN 3 WHEN 'A' THEN 4 ELSE 2 END - CASE '{0}' WHEN 'database' THEN 0 ELSE 2 END)) + N'_' +
convert(nvarchar(10), (CASE WHEN (prmssn.class=4 or prmssn.class=100 )THEN CASE (SELECT oc.type FROM sys.{0}_principals AS oc WHERE oc.principal_id = prmssn.major_id) WHEN 'R' THEN 201 WHEN 'A' THEN 202 ELSE 200 END + CASE prmssn.class WHEN 4 THEN 0 ELSE 100 END ELSE prmssn.class END)) + N'_' +
convert(nvarchar(10), ascii(prmssn.state)) + N'_' +
convert(varchar(10), convert(varbinary(10), prmssn.type))
grantee_principal.nameCASE grantee_principal.type WHEN 'R' THEN 3 WHEN 'A' THEN 4 ELSE 2 END - CASE '{0}' WHEN 'database' THEN 0 ELSE 2 ENDgrantor_principal.nameCASE grantor_principal.type WHEN 'R' THEN 3 WHEN 'A' THEN 4 ELSE 2 END - CASE '{0}' WHEN 'database' THEN 0 ELSE 2 ENDCASE WHEN (prmssn.class=4 or prmssn.class=100 )THEN CASE (SELECT oc.type FROM sys.{0}_principals AS oc WHERE oc.principal_id = prmssn.major_id) WHEN 'R' THEN 201 WHEN 'A' THEN 202 ELSE 200 END + CASE prmssn.class WHEN 4 THEN 0 ELSE 100 END ELSE prmssn.class ENDascii(prmssn.state)prmssn.typeprmssn.stateprmssn.classprmssn.typeprmssn.major_idprmssn.minor_idprmssn.id = 0prmssn.class = 0null
usr.uid >= 16384 and
usr.uid <= 16393 and
spv.type = 'DBR' and
((usr.uid = 16384 and spv.number >= 16384 and spv.number < 16392) or (usr.uid <> 16384 and usr.uid = spv.number)) and
spv.low > 0
usr.namespv.namenull
declare @SmoActiveDirectory sysname
declare @RegPath nvarchar(1024)
select @RegPath = N'Software\Microsoft\MSSQLServer\SQLServerSCP\' + db_name()
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', @RegPath, N'objectGUID', @SmoActiveDirectory OUTPUT
CASE WHEN (@SmoActiveDirectory IS NULL) THEN 0 ELSE 1 END
declare @scmPath sysname
select @scmPath = N'Software\Microsoft\MSSQLServer\SQLServerSCP'
declare @SmoActiveDirectory sysname
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', @scmPath, N'objectGUID', @SmoActiveDirectory OUTPUT
DECLARE @res INT
CREATE table #temp_ad(result BIT)
EXECUTE @res = master.dbo.xp_MSADEnabled
if @res = 0
INSERT INTO #temp_ad VALUES (1)
else
INSERT INTO #temp_ad VALUES (0)
DROP table #temp_ad
ad.resultCASE WHEN (@SmoActiveDirectory IS NULL) THEN 0 ELSE 1 END
DECLARE @instance_name sysname
SELECT @instance_name = null
SELECT @instance_name = N'SQLAgent:'
DECLARE @instance_name sysname
SELECT @instance_name = CONVERT(sysname, SERVERPROPERTY('InstanceName'))
IF @instance_name IS NULL
SELECT @instance_name = N'SQLAgent:'
ELSE
SELECT @instance_name = N'MSSQLAgent$' + @instance_name + N':'
CREATE TABLE #temp_agent_perf_info(object_name nvarchar(256), counter_name nvarchar(256), instance_name nvarchar(256))
CREATE TABLE #temp_job_instances (instance_name nvarchar(20))
INSERT INTO #temp_job_instances VALUES(N'_Total')
INSERT INTO #temp_job_instances VALUES(N'Schedules')
INSERT INTO #temp_job_instances VALUES(N'Alerts')
INSERT INTO #temp_job_instances VALUES(N'Others')
-- Job object
INSERT INTO #temp_agent_perf_info SELECT @instance_name + N'Jobs' , N'Active Jobs', s.instance_name FROM #temp_job_instances s
INSERT INTO #temp_agent_perf_info SELECT @instance_name + N'Jobs' , N'Successful jobs', s.instance_name FROM #temp_job_instances s
INSERT INTO #temp_agent_perf_info SELECT @instance_name + N'Jobs' , N'Failed jobs', s.instance_name FROM #temp_job_instances s
INSERT INTO #temp_agent_perf_info SELECT @instance_name + N'Jobs' , N'Successful jobs ratio', s.instance_name FROM #temp_job_instances s
INSERT INTO #temp_agent_perf_info SELECT @instance_name + N'Jobs' , N'Jobs launched/min', s.instance_name FROM #temp_job_instances s
INSERT INTO #temp_agent_perf_info SELECT @instance_name + N'Jobs' , N'Queued jobs', s.instance_name FROM #temp_job_instances s
--JobStep object
CREATE TABLE #temp_jobstep_instances (subsystem NVARCHAR(40) NULL)
insert #temp_jobstep_instances values('ActiveScripting')
insert #temp_jobstep_instances values('CmdExec')
insert #temp_jobstep_instances values('TSQL')
-- Check if replication is installed
DECLARE @replication_installed int
EXECUTE master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\Replication', N'IsInstalled', @replication_installed OUTPUT, N'no_output'
EXECUTE master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\Replication', N'IsInstalled', @replication_installed OUTPUT, N'no_output'
SELECT @replication_installed = ISNULL(@replication_installed, 0)
if 1 = @replication_installed
begin
insert #temp_jobstep_instances values('Distribution')
insert #temp_jobstep_instances values('LogReader')
insert #temp_jobstep_instances values('Merge')
insert #temp_jobstep_instances values('Snapshot')
end
if 1 = @replication_installed
begin
insert #temp_jobstep_instances values('QueueReader')
end
CREATE TABLE #temp_jobstep_instances (subsystem NVARCHAR(40) NULL, description NVARCHAR(80) NULL, subsystem_dll NVARCHAR(255) NULL, agent_exe NVARCHAR(80) NULL, start_entry_point NVARCHAR(30) NULL, event_entry_point NVARCHAR(30) NULL, stop_entry_point NVARCHAR(30) NULL, max_worker_threads INT NULL, subsystem_id INT NULL)
INSERT #temp_jobstep_instances EXEC msdb.dbo.sp_enum_sqlagent_subsystems
INSERT #temp_jobstep_instances ( subsystem ) VALUES (N'_Total')
INSERT INTO #temp_agent_perf_info SELECT @instance_name + N'JobSteps' , N'Active steps', s.subsystem FROM #temp_jobstep_instances s
INSERT INTO #temp_agent_perf_info SELECT @instance_name + N'JobSteps' , N'Queued steps', s.subsystem FROM #temp_jobstep_instances s
INSERT INTO #temp_agent_perf_info SELECT @instance_name + N'JobSteps' , N'Total Step Retries', s.subsystem FROM #temp_jobstep_instances s
--Alert object
INSERT INTO #temp_agent_perf_info VALUES(@instance_name + N'Alert' , N'Activated Alerts', NULL)
INSERT INTO #temp_agent_perf_info VALUES(@instance_name + N'Alert' , N'Alerts/min', NULL)
--General object
INSERT INTO #temp_agent_perf_info VALUES(@instance_name + N'Statistics' , N'Server Restarted', NULL)
DROP TABLE #temp_job_instances
DROP TABLE #temp_agent_perf_info
DROP TABLE #temp_jobstep_instances
spi.object_namespi.counter_nameISNULL(spi.instance_name,N'')spi.object_namespi.counter_nameISNULL(spi.instance_name,N'')ftl.nameftl.lcid
<
ownobj.type not in ('PK', 'C ', 'F ', 'UQ') and ( ownobj.type != 'D' or 0 = ownobj.parent_object_id)ownobj_parent.object_id = ownobj.parent_object_idnullserverproperty(N'Servername')db_name()ownobj.nameownobj.typeschema_name(ownobj.schema_id)ownobj_parent.nameschema_name(ownobj_parent.schema_id)ownobj.schema_idownobj.schema_id != 4nullserverproperty(N'Servername')db_name()ownobj.nameCASE ownobj.system_type_id WHEN 240 THEN N'UDT' ELSE N'UDDT' ENDschema_name(ownobj.schema_id)nullnullownobj.schema_idownobj.schema_id != 4nullserverproperty(N'Servername')db_name()ownobj.nameN'XMLSCHCOL'schema_name(ownobj.schema_id)nullnullownobj.schema_idownobj.type not in ( 'K', 'S' )ownobj_parent.id = ownobj.parent_objnull@@SERVERNAMEserverproperty(N'Servername')db_name()ownobj.nameownobj.typeuser_name(ownobj.uid)ownobj_parent.nameuser_name(ownobj_parent.uid)ownobj.uidnull@@SERVERNAMEserverproperty(N'Servername')db_name()ownobj.nameN'UDDT'N'dbo'nullnullN'dbo'nullserverproperty(N'Servername')db_name()ownobj.nameN'ASSEMBLY'ownobj.principal_idnullserverproperty(N'Servername')db_name()ownobj.nameN'SCHEMA'ownobj.principal_idCOLUMNPROPERTY(cols.id, cols.name, 'IsFulltextIndexed') <> 0sl.lcid=cols.languagecol.object_id = icol.object_id and col.column_id = icol.column_idsl.lcid=icol.language_idcol2.column_id = icol.type_column_id and col2.object_id = icol.object_idcols.namecols.id(select ISNULL(scol2.name,N'') from
sysdepends as sdep,
syscolumns as scol2
where
cols.colid = sdep.number
and cols.id = sdep.id
and cols.id = scol2.id
and sdep.depnumber = scol2.colid)
(select ISNULL(scol2.name,N'') from
sysdepends as sdep,
syscolumns as scol2
where
cols.colid = sdep.number
and cols.id = sdep.id
and sdep.deptype = 1
and cols.id = scol2.id
and sdep.depnumber = scol2.colid)
sl.aliascol.nameicol.object_idsl.aliasISNULL(col2.name,N'')cat.fulltext_catalog_id = fti.fulltext_catalog_idsi.index_id=fti.unique_index_id and si.object_id=fti.object_idcat.name1fti.is_enabledOBJECTPROPERTY(fti.object_id,'TableFullTextPopulateStatus')(case change_tracking_state when 'M' then 1 when 'A' then 2 else 0 end)OBJECTPROPERTY(fti.object_id,'TableFullTextItemCount')OBJECTPROPERTY(fti.object_id,'TableFullTextDocsProcessed')OBJECTPROPERTY(fti.object_id,'TableFullTextPendingChanges')OBJECTPROPERTY(fti.object_id,'TableFullTextFailCount')fti.object_idsi.name
6
dp1.principal_id = s.principal_ids.names.schema_iddp1.name3s.schema_id0cat.data_space_id = fg.data_space_idci.ftcatid = cat.fulltext_catalog_idcat.principal_id=dp.principal_idci.ftcatid = cat.ftcatid
create table #tmpcatinfo ([ftcatid] smallint,[name] sysname,[path] nvarchar(260),[status] int,[number_fulltext_tables] int)
if( 1 = DATABASEPROPERTYEX(db_name(), 'IsFulltextEnabled') )
begin
insert #tmpcatinfo execute dbo.sp_help_fulltext_catalogs
end
create table #tmpcatinfo ([ftcatid] smallint,[name] sysname,[path] nvarchar(260),[status] int,[number_fulltext_tables] int)
if( 1 = DATABASEPROPERTY(db_name(), 'IsFulltextEnabled') )
begin
insert #tmpcatinfo execute dbo.sp_help_fulltext_catalogs
end
drop table #tmpcatinfo
cat.namecat.fulltext_catalog_idFULLTEXTCATALOGPROPERTY(cat.name,'AccentSensitivity')cat.is_defaultfg.namedp.namecat.ftcatidFULLTEXTCATALOGPROPERTY(cat.name,'LogSize')FULLTEXTCATALOGPROPERTY(cat.name,'IndexSize')FULLTEXTCATALOGPROPERTY(cat.name,'ItemCount')FULLTEXTCATALOGPROPERTY(cat.name,'UniqueKeyCount')FULLTEXTCATALOGPROPERTY(cat.name,'PopulateStatus')FULLTEXTCATALOGPROPERTY(cat.name,'PopulateCompletionAge')GETDATE()0FULLTEXTCATALOGPROPERTY(cat.name,'PopulateCompletionAge')cast(null as datetime)ci.pathci.number_fulltext_tables230
DECLARE @FullTextDefaultPath NVARCHAR(512)
EXECUTE master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE',
N'SOFTWARE\Microsoft\MSSQLServer\MSSQLServer',
N'FullTextDefaultPath',
@FullTextDefaultPath OUTPUT
@@SERVERNAMEserverproperty(N'Servername')ISNULL(FULLTEXTSERVICEPROPERTY('ResourceUsage'), 0)@FullTextDefaultPathISNULL(FULLTEXTSERVICEPROPERTY('ConnectTimeout'),0) * 10000000ISNULL(FULLTEXTSERVICEPROPERTY('DataTimeout'),0) * 100000000CASE
WHEN FULLTEXTSERVICEPROPERTY('VerifySignature') = 0 THEN 1
WHEN FULLTEXTSERVICEPROPERTY('VerifySignature') = 1 THEN 0
ELSE 0 ENDFULLTEXTSERVICEPROPERTY('LoadOSResources')par.is_output = 0par.namepar.parameter_idpar.object_id2par.object_idpar.parameter_id
s
obj.type=N'AF'am.object_id = obj.object_idasmbl.assembly_id = am.assembly_idret_param.object_id = obj.object_id and ret_param.is_output = 1asmbl.nameam.assembly_class
+
asmbl.assembly_id = atypes.assembly_idatypes.user_type_idatypes.max_lengthISNULL(atypes.collation_name,N'')atypes.precisionatypes.scaleatypes.is_nullableasmbl.nameISNULL(atypes.assembly_class,N'')atypes.is_binary_orderedatypes.is_fixed_length00x0060afiles.assembly_idafiles.nameafiles.file_idafiles.content
2
princip.principal_id = asmbl.principal_idasmbl.nameasmbl.assembly_idasmbl.create_dateISNULL(ASSEMBLYPROPERTY(asmbl.assembly_id, N'CultureInfo'), N'')asmbl.permission_setprincip.nameasmbl.is_visibleISNULL(ASSEMBLYPROPERTY(asmbl.name, N'PublicKey'), CONVERT(varbinary(8000), N''))ASSEMBLYPROPERTY(asmbl.name, N'VersionMajor')ASSEMBLYPROPERTY(asmbl.name, N'VersionMinor')ASSEMBLYPROPERTY(asmbl.name, N'VersionBuild')ASSEMBLYPROPERTY(asmbl.name, N'VersionRevision')50
drop table #operator_job_notification_tmp
ont.JobIdont.JobNameont.NotifyLevelEmailont.NotifyLevelNetSendont.NotifyLevelPageont.OperatorName
drop table #operator_notification_tmp
ont.AlertIdont.AlertNameont.UseEmailont.UsePageront.UseNetSendont.HasEmailont.HasPageront.HasNetSendont.OperatorName
t
drop table #alert_notification_tmp
ant.OperatorIdant.OperatorNameant.UseEmailant.UsePagerant.UseNetSendant.HasEmailant.HasPagerant.HasNetSendant.AlertName
C
bkps.backup_set_id = btmp.backup_set_id
declare @server_name nvarchar(512)
set @server_name = @@SERVERNAME
declare @server_name nvarchar(512)
set @server_name = cast(serverproperty(N'Servername') as nvarchar(512))
DECLARE @first_full_backupset_id INTEGER
,@first_full_backup_startdate DATETIME
CREATE TABLE #backupset(
backup_set_id INTEGER NOT NULL
,is_in_restore_plan bit NOT NULL
,backup_start_date datetime NOT NULL
,type CHAR(1) NOT NULL
,database_name nvarchar(256) NOT NULL
)
/**********************************************************************/
/* Identify the first */
/**********************************************************************/
SELECT @first_full_backupset_id = backupset_outer.backup_set_id
,@first_full_backup_startdate = backupset_outer.backup_start_date
FROM msdb.dbo.backupset backupset_outer
WHERE backupset_outer.database_name = @db_name
AND backupset_outer.server_name = @server_name
AND backupset_outer.type = 'D' -- Full Database Backup
AND backupset_outer.backup_start_date = ( SELECT MAX(backupset_inner.backup_start_date)
FROM msdb.dbo.backupset backupset_inner
WHERE backupset_inner.database_name = backupset_outer.database_name
AND backupset_inner.server_name = @server_name
AND backupset_inner.type = backupset_outer.type AND
backupset_inner.backup_start_date <= @restore_to_datetime)
/*******************************************************************************************/
/* Find the first full database backup needed in the restore plan and store its attributes */
/* in #backupset work table */
/*******************************************************************************************/
INSERT #backupset(
backup_set_id
,is_in_restore_plan
,backup_start_date
,type
,database_name
)
SELECT backup_set_id
,1 -- The full database backup is always needed for the restore plan
,backup_start_date
,type
,database_name
FROM msdb.dbo.backupset
WHERE msdb.dbo.backupset.backup_set_id = @first_full_backupset_id
AND msdb.dbo.backupset.server_name = @server_name
/***************************************************************/
/* Find the log and differential backups that occurred after */
/* the full backup and store them in #backupset work table */
/***************************************************************/
INSERT #backupset(
backup_set_id
,is_in_restore_plan
,backup_start_date
,type
,database_name
)
SELECT backup_set_id
,0
,backup_start_date
,type
,database_name
FROM msdb.dbo.backupset
WHERE msdb.dbo.backupset.database_name = @db_name
AND msdb.dbo.backupset.server_name = @server_name
AND msdb.dbo.backupset.type IN ('I', 'L') -- Differential, Log backups
AND msdb.dbo.backupset.backup_start_date >= @first_full_backup_startdate
/**********************************************************************************/
/* identify and mark the backup logs that need to be included in the restore plan */
/**********************************************************************************/
UPDATE #backupset
SET is_in_restore_plan = 1
WHERE #backupset.type = 'I'
AND #backupset.backup_start_date = (SELECT MAX(backupset_inner.backup_start_date)
FROM #backupset backupset_inner
WHERE backupset_inner.type = #backupset.type
AND backupset_inner.backup_start_date <= @restore_to_datetime)
/**************************************************************************************/
/* Log backups that occurred after the different are always part of the restore plan. */
/**************************************************************************************/
UPDATE #backupset
SET is_in_restore_plan = 1
WHERE #backupset.type = 'L'
AND #backupset.backup_start_date <= @restore_to_datetime
AND #backupset.backup_start_date >= (SELECT backupset_inner.backup_start_date
FROM #backupset backupset_inner
WHERE backupset_inner.type = 'I'
AND backupset_inner.is_in_restore_plan = 1)
/**************************************************************************************/
/* If @restore_to_datetime is greater than the last startdate of the last log backup, */
/* include the next log backup in the restore plan */
/**************************************************************************************/
UPDATE #backupset
SET is_in_restore_plan = 1
WHERE #backupset.type = 'L'
AND #backupset.backup_start_date = (SELECT MIN(backupset_inner.backup_start_date)
FROM #backupset backupset_inner
WHERE backupset_inner.type = 'L'
AND backupset_inner.backup_start_date > @restore_to_datetime
AND backupset_inner.is_in_restore_plan = 0)
/**************************************************************************************/
/* If there are no differential backups, all log backups that occurred after the full */
/* backup are needed in the restore plan. */
/**************************************************************************************/
UPDATE #backupset
SET is_in_restore_plan = 1
WHERE #backupset.type = 'L'
AND #backupset.backup_start_date <= @restore_to_datetime
AND NOT EXISTS(SELECT *
FROM #backupset backupset_inner
WHERE backupset_inner.type = 'I')
DECLARE @first_full_backupset_id INTEGER
,@first_full_backup_startdate DATETIME
CREATE TABLE #backupset(
backup_set_id INTEGER NOT NULL
,is_in_restore_plan bit NOT NULL
,backup_start_date datetime NOT NULL
,type CHAR(1) NOT NULL
,database_name nvarchar(256) NOT NULL
)
/**********************************************************************/
/* Identify the first */
/**********************************************************************/
SELECT @first_full_backupset_id = backupset_outer.backup_set_id
,@first_full_backup_startdate = backupset_outer.backup_start_date
FROM msdb.dbo.backupset backupset_outer
WHERE backupset_outer.database_name = @db_name
AND backupset_outer.server_name = @server_name
AND backupset_outer.type = 'D' -- Full Database Backup
AND backupset_outer.backup_start_date = ( SELECT MAX(backupset_inner.backup_start_date)
FROM msdb.dbo.backupset backupset_inner
WHERE backupset_inner.database_name = backupset_outer.database_name
AND backupset_inner.server_name = @server_name
AND backupset_inner.type = backupset_outer.type
AND backupset_inner.backup_start_date <= @restore_to_datetime
AND backupset_inner.is_copy_only = 0 )
AND backupset_outer.is_copy_only = 0
/*******************************************************************************************/
/* Find the first full database backup needed in the restore plan and store its attributes */
/* in #backupset work table */
/*******************************************************************************************/
INSERT #backupset(
backup_set_id
,is_in_restore_plan
,backup_start_date
,type
,database_name
)
SELECT backup_set_id
,1 -- The full database backup is always needed for the restore plan
,backup_start_date
,type
,database_name
FROM msdb.dbo.backupset
WHERE msdb.dbo.backupset.backup_set_id = @first_full_backupset_id
AND msdb.dbo.backupset.server_name = @server_name
/***************************************************************/
/* Find the log and differential backups that occurred after */
/* the full backup and store them in #backupset work table */
/***************************************************************/
INSERT #backupset(
backup_set_id
,is_in_restore_plan
,backup_start_date
,type
,database_name
)
SELECT backup_set_id
,0
,backup_start_date
,type
,database_name
FROM msdb.dbo.backupset
WHERE msdb.dbo.backupset.database_name = @db_name
AND msdb.dbo.backupset.server_name = @server_name
AND msdb.dbo.backupset.type IN ('I', 'L') -- Differential, Log backups
AND msdb.dbo.backupset.backup_start_date >= @first_full_backup_startdate
/**********************************************************************************/
/* identify and mark the backup logs that need to be included in the restore plan */
/**********************************************************************************/
UPDATE #backupset
SET is_in_restore_plan = 1
WHERE #backupset.type = 'I'
AND #backupset.backup_start_date = (SELECT MAX(backupset_inner.backup_start_date)
FROM #backupset backupset_inner
WHERE backupset_inner.type = #backupset.type
AND backupset_inner.backup_start_date <= @restore_to_datetime)
/**************************************************************************************/
/* Log backups that occurred after the different are always part of the restore plan. */
/**************************************************************************************/
UPDATE #backupset
SET is_in_restore_plan = 1
WHERE #backupset.type = 'L'
AND #backupset.backup_start_date <= @restore_to_datetime
AND #backupset.backup_start_date >= (SELECT backupset_inner.backup_start_date
FROM #backupset backupset_inner
WHERE backupset_inner.type = 'I'
AND backupset_inner.is_in_restore_plan = 1)
/**************************************************************************************/
/* If @restore_to_datetime is greater than the last startdate of the last log backup, */
/* include the next log backup in the restore plan */
/**************************************************************************************/
UPDATE #backupset
SET is_in_restore_plan = 1
WHERE #backupset.type = 'L'
AND #backupset.backup_start_date = (SELECT MIN(backupset_inner.backup_start_date)
FROM #backupset backupset_inner
WHERE backupset_inner.type = 'L'
AND backupset_inner.backup_start_date > @restore_to_datetime
AND backupset_inner.is_in_restore_plan = 0)
/**************************************************************************************/
/* If there are no differential backups, all log backups that occurred after the full */
/* backup are needed in the restore plan. */
/**************************************************************************************/
UPDATE #backupset
SET is_in_restore_plan = 1
WHERE #backupset.type = 'L'
AND #backupset.backup_start_date <= @restore_to_datetime
AND NOT EXISTS(SELECT *
FROM #backupset backupset_inner
WHERE backupset_inner.type = 'I')
drop table #backupset
bkps.namebkps.backup_set_idbtmp.is_in_restore_planbkps.backup_set_uuidbkps.media_set_idbkps.first_family_numberbkps.first_media_numberbkps.last_family_numberbkps.last_media_numberbkps.catalog_family_numberbkps.catalog_media_numberbkps.positionbkps.expiration_datebkps.software_vendor_idbkps.descriptionbkps.user_namebkps.software_major_versionbkps.software_minor_versionbkps.software_build_versionbkps.time_zonebkps.mtf_minor_versionbkps.first_lsnbkps.last_lsnbkps.checkpoint_lsnbkps.database_backup_lsnbkps.database_creation_datebkps.backup_start_datebkps.backup_finish_datebkps.typebkps.sort_orderbkps.code_pagebkps.compatibility_levelbkps.database_versionbkps.backup_sizebkps.database_namebkps.server_namebkps.machine_namebkps.flagsbkps.unicode_localebkps.unicode_compare_stylebkps.collation_name
H
am{0}.object_id = {0}.object_idasmbl{0}.assembly_id = am{0}.assembly_idcase when am{0}.object_id is null then N'' else asmbl{0}.name endcase when am{0}.object_id is null then N'' else am{0}.assembly_class endcase when am{0}.object_id is null then N'' else am{0}.assembly_method endsm{0}.object_id = {0}.object_idssm{0}.object_id = {0}.object_idOBJECTPROPERTYEX({0}.object_id,N'ExecIsAnsiNullsOn')OBJECTPROPERTYEX({0}.object_id,N'ExecIsQuotedIdentOn')OBJECTPROPERTYEX({0}.object_id, N'IsSchemaBound')sm{0}.null_on_null_inputcase isnull(sm{0}.execute_as_principal_id, -1) when -1 then 1 when -2 then 2 else 3 endcase isnull(sm{0}.execute_as_principal_id, -1) when -1 then 1 else 2 endISNULL(user_name(sm{0}.execute_as_principal_id),N'')tbl.id = {0}.idtbl.object_id = {0}.object_id{0}.nametbl.nameuser_name(tbl.uid)schema_name(tbl.schema_id)
f
s{0}.uid = {0}.uids{0}.schema_id = {0}.schema_id{0}.names{0}.namep.major_id=0 AND p.minor_id=0 AND p.class=0p.namep.value
create table #extprops(owner sysname null, parentobjname sysname null,
objname sysname null, name sysname , value sql_variant null)
drop table #extprops
cast(p.owner as varbinary(256))cast(p.parentobjname as varbinary(256))cast(p.objname as varbinary(256))
<
create table #extprops(owner sysname null, parentobjname sysname null,
objname sysname null, name sysname , value sql_variant null)
drop table #extprops
cast(p.owner as varbinary(256))cast(p.parentobjname as varbinary(256))cast(p.objname as varbinary(256))
<
create table #extprops(owner sysname null, objname sysname null, name sysname, value sql_variant null)
drop table #extprops
cast(p.owner as varbinary(256))cast(p.objname as varbinary(256))cast(p.objname as varbinary(256))p.namep.valuep.namep.valuep.idp.smallidp.typep.major_idp.minor_idp.classusrt.xusertype = {0}.xusertypebaset.xusertype = {0}.xtype and baset.xusertype = baset.xtypes{0}.uid = usrt.uidusrt.user_type_id = {0}.user_type_idbaset.user_type_id = {0}.system_type_id and baset.user_type_id = baset.system_type_ids{0}.schema_id = usrt.schema_idxsc{0}.xml_collection_id = {0}.xml_collection_ids2{0}.schema_id = xsc{0}.schema_idusrt.names{0}.namebaset.nameISNULL(baset.name, N'')CASE WHEN baset.name IN (N'char', N'varchar', N'binary', N'varbinary', N'nchar', N'nvarchar') THEN {0}.prec ELSE {0}.length END{0}.xprec{0}.xscaleCASE WHEN baset.name IN (N'nchar', N'nvarchar') AND {0}.max_length <> -1 THEN {0}.max_length/2 ELSE {0}.max_length END{0}.precision{0}.scaleISNULL(xsc{0}.name, N'')ISNULL(s2{0}.name, N'')ISNULL( (case {0}.is_xml_document when 1 then 2 else 1 end), 0)fg{0}.groupnameCASE WHEN 'FG'=ds{0}.type THEN ds{0}.name ELSE N'' ENDCASE WHEN 'PS'=ds{0}.type THEN ds{0}.name ELSE N'' ENDCASE WHEN 'PS'=ds{0}.type THEN 1 ELSE 0 ENDsf.data_space_id = sdd.data_space_idsf.namesdd.destination_idsps.function_id = spf.function_id sps.namesps.data_space_idspf.fanoutspf.nameISNULL((case when spf.fanout < (select count(*) from sys.destination_data_spaces sdd where sps.data_space_id = sdd.partition_scheme_id) then (select sf.name from sys.filegroups sf, sys.destination_data_spaces sdd where sf.data_space_id = sdd.data_space_id and sps.data_space_id = sdd.partition_scheme_id and sdd.destination_id > spf.fanout) else null end),N'')20sps.data_space_id0sprv.boundary_idsprv.function_idsprv.valuest.system_type_id = st.user_type_id and spp.system_type_id = st.system_type_idspp.parameter_idspp.function_idISNULL(spp.collation_name,N'')spf.namespf.function_idspf.boundary_value_on_rightspf.create_datespf.fanout21spf.function_id0
L
ic.partition_ordinal > 0c.object_id = ic.object_id and c.column_id = ic.column_idc.nameic.partition_ordinalic.index_idic.object_idcstr.status & 41 - ISNULL(OBJECTPROPERTY(cstr.id, N'CnstIsNotTrusted'),0)1 - ISNULL(OBJECTPROPERTY(cstr.id, N'CnstIsDisabled'),0)ISNULL(OBJECTPROPERTY(cstr.id, N'CnstIsNotRepl'),0)N'CONSTRAINT'cstr.is_system_named~cstr.is_not_trusted~cstr.is_disabledcstr.is_not_for_replication0
CASE WHEN (OBJECTPROPERTY({0}.id, N'IsMSShipped')=1) THEN 1 WHEN 1 = OBJECTPROPERTY({0}.id, N'IsSystemTable') THEN 1 ELSE 0 END
case
when {0}.is_ms_shipped = 1 then 1
when (
select
major_id
from
sys.extended_properties
where
major_id = {0}.object_id and
minor_id = 0 and
class = 1 and
name = N'microsoft_database_tools_support')
is not null then 1
else 0
end
CASE WHEN (OBJECTPROPERTY({0}.id, N'IsMSShipped')=1) THEN 1 WHEN 1 = OBJECTPROPERTY({0}.id, N'IsSystemTable') THEN 1 ELSE 0 END
{0}.is_ms_shipped
s{0}.uid = {0}.uids{0}.nameSCHEMA_NAME({0}.schema_id)comt.colidcomt.textcast(comt.id as nvarchar(20)) + N'_' + cast(comt.number as nvarchar(20)) + N'_' + cast(db_id() as nvarchar(20)) + N'_0'comt.idcomt.numbercfk.colid=fk.fkey and cfk.id = fk.fkeyidcrk.colid=fk.rkey and crk.id = fk.rkeyidfk.parent_column_id = cfk.column_id and fk.parent_object_id = cfk.object_idfk.referenced_column_id = crk.column_id and fk.referenced_object_id = crk.object_idcfk.namefk.keynocrk.namefk.constidcfk.namefk.constraint_column_idcrk.namefk.constraint_object_id
declare @NumErrorLogs int
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'NumErrorLogs', @NumErrorLogs OUTPUT
declare @SmoDefaultFile nvarchar(512)
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultData', @SmoDefaultFile OUTPUT
declare @SmoDefaultLog nvarchar(512)
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultLog', @SmoDefaultLog OUTPUT
declare @SmoLoginMode int
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'LoginMode', @SmoLoginMode OUTPUT
declare @SmoAuditLevel int
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'AuditLevel', @SmoAuditLevel OUTPUT
declare @SmoTapeLoadWaitTime int
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'Tapeloadwaittime', @SmoTapeLoadWaitTime OUTPUT
declare @BackupDirectory nvarchar(512)
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'BackupDirectory', @BackupDirectory OUTPUT
declare @SmoMailProfile nvarchar(512)
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'MailAccountName', @SmoMailProfile OUTPUT
declare @SmoPerfMonMode int
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'Performance', @SmoPerfMonMode OUTPUT
if @SmoPerfMonMode is null
begin
set @SmoPerfMonMode = 1000
end
declare @NumErrorLogs int
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'NumErrorLogs', @NumErrorLogs OUTPUT
declare @SmoDefaultFile nvarchar(512)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultData', @SmoDefaultFile OUTPUT
declare @SmoDefaultLog nvarchar(512)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultLog', @SmoDefaultLog OUTPUT
declare @SmoLoginMode int
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'LoginMode', @SmoLoginMode OUTPUT
declare @SmoAuditLevel int
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'AuditLevel', @SmoAuditLevel OUTPUT
declare @SmoTapeLoadWaitTime int
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'Tapeloadwaittime', @SmoTapeLoadWaitTime OUTPUT
declare @BackupDirectory nvarchar(512)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'BackupDirectory', @BackupDirectory OUTPUT
declare @SmoMailProfile nvarchar(512)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'MailAccountName', @SmoMailProfile OUTPUT
declare @SmoPerfMonMode int
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'Performance', @SmoPerfMonMode OUTPUT
if @SmoPerfMonMode is null
begin
set @SmoPerfMonMode = 1000
end
@SmoAuditLevelISNULL(@SmoDefaultFile,N'')ISNULL(@SmoDefaultLog,N'')ISNULL(@NumErrorLogs, -1)(case when @SmoLoginMode < 3 then @SmoLoginMode else 9 end)@SmoTapeLoadWaitTimeISNULL(@SmoMailProfile,N'')@BackupDirectory@SmoPerfMonMode
create table #SVer(ID int, Name sysname, Internal_Value int, Value nvarchar(512))
insert #SVer exec master.dbo.xp_msver
declare @NetName sysname
exec master.dbo.xp_getnetname @NetName OUTPUT
declare @SmoRoot nvarchar(512)
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\Setup', N'SQLPath', @SmoRoot OUTPUT
declare @RegPathParams sysname
declare @Arg sysname
declare @Param sysname
declare @MasterPath nvarchar(512)
declare @LogPath nvarchar(512)
declare @ErrorLogPath nvarchar(512)
declare @n int
select @n=0
select @RegPathParams=N'Software\Microsoft\MSSQLServer\MSSQLServer'+'\Parameters'
select @Param='dummy'
while(not @Param is null)
begin
select @Param=null
select @Arg='SqlArg'+convert(nvarchar,@n)
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', @RegPathParams, @Arg, @Param OUTPUT
if(@Param like '-d%')
begin
select @Param=substring(@Param, 3, 255)
select @MasterPath=substring(@Param, 1, len(@Param) - charindex('\', reverse(@Param)))
end
else if(@Param like '-l%')
begin
select @Param=substring(@Param, 3, 255)
select @LogPath=substring(@Param, 1, len(@Param) - charindex('\', reverse(@Param)))
end
else if(@Param like '-e%')
begin
select @Param=substring(@Param, 3, 255)
select @ErrorLogPath=substring(@Param, 1, len(@Param) - charindex('\', reverse(@Param)))
end
select @n=@n+1
end
drop table #SVer
create table #SVer(ID int, Name sysname, Internal_Value int, Value nvarchar(512))
insert #SVer exec master.dbo.xp_msver
declare @SmoRoot nvarchar(512)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\Setup', N'SQLPath', @SmoRoot OUTPUT
declare @RegPathParams sysname
declare @Arg sysname
declare @Param sysname
declare @MasterPath nvarchar(512)
declare @LogPath nvarchar(512)
declare @ErrorLogPath nvarchar(512)
declare @n int
select @n=0
select @RegPathParams=N'Software\Microsoft\MSSQLServer\MSSQLServer'+'\Parameters'
select @Param='dummy'
while(not @Param is null)
begin
select @Param=null
select @Arg='SqlArg'+convert(nvarchar,@n)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', @RegPathParams, @Arg, @Param OUTPUT
if(@Param like '-d%')
begin
select @Param=substring(@Param, 3, 255)
select @MasterPath=substring(@Param, 1, len(@Param) - charindex('\', reverse(@Param)))
end
else if(@Param like '-l%')
begin
select @Param=substring(@Param, 3, 255)
select @LogPath=substring(@Param, 1, len(@Param) - charindex('\', reverse(@Param)))
end
else if(@Param like '-e%')
begin
select @Param=substring(@Param, 3, 255)
select @ErrorLogPath=substring(@Param, 1, len(@Param) - charindex('\', reverse(@Param)))
end
select @n=@n+1
end
drop table #SVer
(select Value from #SVer where Name = N'ProductName')(select Value from #SVer where Name = N'WindowsVersion')(select Value from #SVer where Name = N'Language')(select Value from #SVer where Name = N'Platform')(select Internal_Value from #SVer where Name = N'PhysicalMemory')(select Internal_Value from #SVer where Name = N'ProcessorCount')(@@microsoftversion / 0x1000000) & 0xff(@@microsoftversion / 0x10000) & 0xff@@microsoftversion & 0xffffcase when 'a' <> 'A' then 1 else 0 endFULLTEXTSERVICEPROPERTY('IsFullTextInstalled')@LogPath@MasterPath@ErrorLogPath@@MAX_PRECISION@SmoRoot(select Value from #SVer where Name = N'ProductVersion')@NetNameSUBSTRING(@@version,PATINDEX(N'%Corporation%',@@version)+DATALENGTH('Corporation')+2,PATINDEX(N'% on %',@@version)-(PATINDEX(N'%Corporation%',@@version)+DATALENGTH('Corporation')+2))SERVERPROPERTY(N'ProductVersion')SERVERPROPERTY(N'MachineName')SERVERPROPERTY(N'Edition')SERVERPROPERTY(N'ProductLevel')SERVERPROPERTY('IsClustered')SERVERPROPERTY('IsSingleUser')SERVERPROPERTY('EngineEdition')case when (select password from master.dbo.syslogins where sid = 0x01) is null then 1 else 0 endnullconvert(sysname, serverproperty(N'collation'))
I
declare @UserOption int
select @UserOption=c.value from master.dbo.sysconfigures c, master.dbo.spt_values v where v.type = 'C ' and not c.status is null and v.number = c.config and v.name='user options'
declare @UserOption int
select @UserOption=c.value from sys.sysconfigures c where not c.status is null and c.comment='user options'
@UserOption & 1@UserOption & 2@UserOption & 4@UserOption & 8@UserOption & 16@UserOption & 32@UserOption & 64@UserOption & 128@UserOption & 256@UserOption & 512@UserOption & 1024@UserOption & 2048@UserOption & 4096@UserOption & 8192@UserOption & 16384
clmns.id = c.id and clmns.colid = c.colid
clmns.namec.keynoc.idc.indidc.colidCOL_NAME(sic.object_id, sic.column_id)sic.stats_column_idsic.object_idsic.stats_idsic.column_idconvert(nchar(1), am.name)= convert(nchar(1), srddrv.DriveName)
create table #avmed (name nvarchar(512), low_free int, high_free int, type int)
insert #avmed exec master.dbo.xp_availablemedia
update #avmed set name = convert(nchar(2), name)
create table #tmpsrdDrive ( DriveName nvarchar(255) )
insert #tmpsrdDrive select * from ::fn_servershareddrives()
create table #tmpsrdDrive ( DriveName nvarchar(255) )
insert #tmpsrdDrive select * from sys.fn_servershareddrives()
drop table #avmed
drop table #tmpsrdDrive
am.nameam.low_freeam.high_freecase when am.low_free >= 0 then 0. + am.low_free else 4294967296. + am.low_free end + 4294967296. * am.high_freeam.typecase when srddrv.DriveName is null then 0 else 1 end
drop table #err_log_text_tmp
ert.LogDateert.ErrorLevelert.Textert.ArchiveNo
create table #err_log_tmp(ArchiveNo int, CreateDate nvarchar(24), Size int)
insert #err_log_tmp exec master.dbo.sp_enumerrorlogs 2
create table #err_log_tmp(ArchiveNo int, CreateDate datetime, Size int, ErrorLog NVARCHAR(255))
DECLARE @errorlog_path NVARCHAR(255)
DECLARE @errorlog_dir NVARCHAR(255)
DECLARE @errorlog_partfile NVARCHAR(255)
DECLARE @errorlog NVARCHAR(255)
DECLARE @dotIdx INT
DECLARE @slashIdx INT
DECLARE @logexists INT
DECLARE @ArchiveNo INT
EXECUTE master.dbo.xp_regread N'HKEY_LOCAL_MACHINE',
N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent',
N'ErrorLogFile',
@errorlog_path OUTPUT,
N'no_output'
EXECUTE master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE',
N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent',
N'ErrorLogFile',
@errorlog_path OUTPUT,
N'no_output'
-->
EXECUTE master.dbo.xp_fileexist @errorlog_path, @logexists OUTPUT
IF(@logexists = 1)
BEGIN
create table #err_logs_dir_tmp(ErrorLog NVARCHAR(255), d int, f int)
create table #file_details_tmp(AltName NVARCHAR(32) NULL, Size int, CDate INT, CTime INT, LWDate INT, LWTime INT, LADate INT, LATime INT, Attributes INT)
INSERT #file_details_tmp EXECUTE master.dbo.xp_getfiledetails @errorlog_path
SET @errorlog_path = REVERSE(@errorlog_path)
SET @dotIdx = CHARINDEX(N'.', @errorlog_path);
SET @slashIdx = CHARINDEX(N'\', @errorlog_path);
SET @errorlog_path = REVERSE(@errorlog_path)
SET @errorlog_dir = @errorlog_path
if(@slashIdx <> 0)
BEGIN
SET @errorlog_dir = SUBSTRING(@errorlog_path, 1, LEN(@errorlog_path) - @slashIdx)
SET @errorlog_partfile= SUBSTRING(@errorlog_path, LEN(@errorlog_path) - @slashIdx + 2, 255)
END
if(@dotIdx <> 0)
BEGIN
SET @errorlog_partfile = SUBSTRING(@errorlog_partfile, 1, LEN(@errorlog_partfile) - @dotIdx + 1)
END
INSERT #err_logs_dir_tmp EXECUTE master.dbo.xp_dirtree @errorlog_dir, 1, 1
INSERT #err_log_tmp(ArchiveNo, CreateDate, Size, ErrorLog)
SELECT
0,
-- convert the 2 int's (20020912 152026) to yyyy-mm-dd hh:mi:ss
CONVERT(datetime, STUFF(STUFF(STR(LWDate, 8), 7, 0, '-'), 5, 0, '-') + ' ' +
STUFF(STUFF(REPLACE(STR(LWTime,6), ' ', '0'), 5, 0, ':'), 3, 0, ':')
, 120),
Size,
@errorlog_path
FROM #file_details_tmp
DELETE #file_details_tmp
declare crslogs insensitive cursor
for ( SELECT ErrorLog FROM #err_logs_dir_tmp WHERE ErrorLog like @errorlog_partfile + '[1-9]' )
for read only
open crslogs
fetch crslogs into @errorlog
while @@fetch_status >= 0
begin
SET @ArchiveNo = CONVERT(INT, SUBSTRING(@errorlog, LEN(@errorlog_partfile) + 1, 1))
SET @errorlog = @errorlog_dir + '\' + @errorlog
INSERT #file_details_tmp EXECUTE master.dbo.xp_getfiledetails @errorlog
INSERT #err_log_tmp(ArchiveNo, CreateDate, Size, ErrorLog)
SELECT
@ArchiveNo,
-- convert the 2 int's (20020912 152026) to yyyy-mm-dd hh:mi:ss
CONVERT(datetime, STUFF(STUFF(STR(LWDate, 8), 7, 0, '-'), 5, 0, '-') + ' ' +
STUFF(STUFF(REPLACE(STR(LWTime,6), ' ', '0'), 5, 0, ':'), 3, 0, ':')
, 120),
Size,
@errorlog
FROM #file_details_tmp
DELETE #file_details_tmp
fetch crslogs into @errorlog
end
close crslogs
deallocate crslogs
DROP TABLE #file_details_tmp
DROP TABLE #err_logs_dir_tmp
END
drop table #err_log_tmp
er.ArchiveNoer.ArchiveNoer.CreateDateCONVERT(datetime, er.CreateDate, 101)er.Size
drop table #tmp_sp_help_jobserver
tshj.server_nametshj.server_idtshj.enlist_datetshj.last_poll_datenulltshj.last_run_datetshj.last_run_timetshj.last_run_durationtshj.last_run_outcometshj.last_outcome_messagetshj.job_id
create table #tmp_sp_help_jobhistory
(instance_id int null, job_id uniqueidentifier null, job_name nvarchar(128) null, step_id int null, step_name nvarchar(128) null, sql_message_id int null, sql_severity int null, message nvarchar(1024) null, run_status int null, run_date int null, run_time int null, run_duration int null, operator_emailed nvarchar(128) null, operator_netsent nvarchar(128) null, operator_paged nvarchar(128) null, retries_attempted int null, server nvarchar(30) null)
insert into #tmp_sp_help_jobhistory exec msdb.dbo.sp_help_jobhistory @mode='FULL'
drop table #tmp_sp_help_jobhistory
tshj.instance_idtshj.sql_message_idtshj.messagetshj.step_idtshj.step_nametshj.sql_severitytshj.job_idtshj.job_nametshj.run_statusconvert(datetime, stuff(stuff(cast(tshj.run_date as nchar(8)), 7, 0, '-'), 5, 0, '-') + N' ' + stuff(stuff(substring(cast(1000000 + tshj.run_time as nchar(7)), 2, 6), 5, 0, ':'), 3, 0, ':'), 120)tshj.run_durationtshj.operator_emailedtshj.operator_netsenttshj.operator_pagedtshj.retries_attemptedtshj.server
"
&
{0}.definition
drop table #tmp_sp_help_targetservergroup_member
tshtm.server_nametshtm.server_idtshtm.servergroup_name
create table #tmp_sp_help_targetservergroup
(servergroup_id int null, name nvarchar(128) null)
insert into #tmp_sp_help_targetservergroup exec msdb..sp_help_targetservergroup
drop table #tmp_sp_help_targetservergroup
tsht.nametsht.servergroup_id
"
declare @FailSafeOperator nvarchar(255)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'AlertFailSafeOperator', @param = @FailSafeOperator OUT, @no_output = N'no_output'
declare @NotificationMethod int
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'AlertNotificationMethod', @param = @NotificationMethod OUT, @no_output = N'no_output'
declare @ForwardingServer nvarchar(255)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'AlertForwardingServer', @param = @ForwardingServer OUT, @no_output = N'no_output'
declare @ForwardingSeverity int
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'AlertForwardingSeverity', @param = @ForwardingSeverity OUT, @no_output = N'no_output'
declare @ForwardAlways int
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'AlertForwardAlways', @param = @ForwardAlways OUT, @no_output = N'no_output'
declare @PagerToTemplate nvarchar(255)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'AlertPagerToTemplate', @param = @PagerToTemplate OUT, @no_output = N'no_output'
declare @PagerCCTemplate nvarchar(255)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'AlertPagerCCTemplate', @param = @PagerCCTemplate OUT, @no_output = N'no_output'
declare @PagerSubjectTemplate nvarchar(255)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'AlertPagerSubjectTemplate', @param = @PagerSubjectTemplate OUT, @no_output = N'no_output'
declare @PagerSendSubjectOnly int
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'AlertPagerSendSubjectOnly', @param = @PagerSendSubjectOnly OUT, @no_output = N'no_output'
declare @FailSafeEmailAddress nvarchar(255)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'AlertFailSafeEmailAddress', @param = @FailSafeEmailAddress OUT, @no_output = N'no_output'
declare @FailSafePagerAddress nvarchar(255)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'AlertFailSafePagerAddress', @param = @FailSafePagerAddress OUT, @no_output = N'no_output'
declare @FailSafeNetSendAddress nvarchar(255)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'AlertFailSafeNetSendAddress', @param = @FailSafeNetSendAddress OUT, @no_output = N'no_output'
declare @FailSafeOperator nvarchar(255)
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'AlertFailSafeOperator', @param = @FailSafeOperator OUT, @no_output = N'no_output'
declare @NotificationMethod int
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'AlertNotificationMethod', @param = @NotificationMethod OUT, @no_output = N'no_output'
declare @ForwardingServer nvarchar(255)
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'AlertForwardingServer', @param = @ForwardingServer OUT, @no_output = N'no_output'
declare @ForwardingSeverity int
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'AlertForwardingSeverity', @param = @ForwardingSeverity OUT, @no_output = N'no_output'
declare @ForwardAlways int
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'AlertForwardAlways', @param = @ForwardAlways OUT, @no_output = N'no_output'
declare @PagerToTemplate nvarchar(255)
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'AlertPagerToTemplate', @param = @PagerToTemplate OUT, @no_output = N'no_output'
declare @PagerCCTemplate nvarchar(255)
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'AlertPagerCCTemplate', @param = @PagerCCTemplate OUT, @no_output = N'no_output'
declare @PagerSubjectTemplate nvarchar(255)
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'AlertPagerSubjectTemplate', @param = @PagerSubjectTemplate OUT, @no_output = N'no_output'
declare @PagerSendSubjectOnly int
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'AlertPagerSendSubjectOnly', @param = @PagerSendSubjectOnly OUT, @no_output = N'no_output'
declare @FailSafeEmailAddress nvarchar(255)
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'AlertFailSafeEmailAddress', @param = @FailSafeEmailAddress OUT, @no_output = N'no_output'
declare @FailSafePagerAddress nvarchar(255)
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'AlertFailSafePagerAddress', @param = @FailSafePagerAddress OUT, @no_output = N'no_output'
declare @FailSafeNetSendAddress nvarchar(255)
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'AlertFailSafeNetSendAddress', @param = @FailSafeNetSendAddress OUT, @no_output = N'no_output'
N'AlertSystem'ISNULL(@FailSafeOperator,N'')@NotificationMethodISNULL(@ForwardingServer,N'')@ForwardingSeverityISNULL(@ForwardAlways, 0)ISNULL(@PagerToTemplate,N'')ISNULL(@PagerCCTemplate,N'')ISNULL(@PagerSubjectTemplate,N'')@PagerSendSubjectOnlyISNULL(@FailSafeEmailAddress,N'')ISNULL(@FailSafePagerAddress,N'')ISNULL(@FailSafeNetSendAddress,N'')
create table #tmp_sp_help_targetserver
(server_id int null, server_name nvarchar(30) null, location nvarchar(200) null, time_zone_adjustment int null, enlist_date datetime null, last_poll_date datetime null, status int null, unread_instructions int null, local_time datetime null, enlisted_by_nt_user nvarchar(200) null, poll_interval int null)
insert into #tmp_sp_help_targetserver exec msdb.dbo.sp_help_targetserver
drop table #tmp_sp_help_targetserver
tsht.server_nametsht.server_idtsht.locationtsht.time_zone_adjustmenttsht.enlist_datetsht.last_poll_datetsht.statustsht.poll_intervaltsht.unread_instructionstsht.local_time
create table #tmp_sp_help_operator
(id int null, name nvarchar(128) null, enabled tinyint null, email_address nvarchar(100) null, last_email_date int null, last_email_time int null, pager_address nvarchar(100) null, last_pager_date int null, last_pager_time int null, weekday_pager_start_time int null, weekday_pager_end_time int null, saturday_pager_start_time int null, saturday_pager_end_time int null, sunday_pager_start_time int null, sunday_pager_end_time int null, pager_days tinyint null, netsend_address nvarchar(100) null, last_netsend_date int null, last_netsend_time int null, category_name nvarchar(128) null)
insert into #tmp_sp_help_operator exec msdb.dbo.sp_help_operator
drop table #tmp_sp_help_operator
tsho.nametsho.idtsho.enabledISNULL(tsho.email_address,N'')nulltsho.last_email_datetsho.last_email_timeISNULL(tsho.pager_address,N'')nulltsho.last_pager_datetsho.last_pager_time0tsho.weekday_pager_start_time0tsho.weekday_pager_end_time0tsho.saturday_pager_start_time0tsho.saturday_pager_end_time0tsho.sunday_pager_start_time0tsho.sunday_pager_end_timetsho.pager_daysISNULL(tsho.netsend_address,N'')nulltsho.last_netsend_datetsho.last_netsend_timeISNULL(tsho.category_name,N'')
Z
create table #tmp_sp_help_alert
(id int null, name nvarchar(128) null, event_source nvarchar(100) null, event_category_id int null, event_id int null, message_id int null, severity int null, enabled tinyint null, delay_between_responses int null, last_occurrence_date int null, last_occurrence_time int null, last_response_date int null, last_response_time int null, notification_message nvarchar(512) null, include_event_description tinyint null, database_name nvarchar(128) null, event_description_keyword nvarchar(100) null, occurrence_count int null, count_reset_date int null, count_reset_time int null, job_id uniqueidentifier null, job_name nvarchar(128) null, has_notification int null, flags int null, performance_condition nvarchar(512) null, category_name nvarchar(128) null, type int null)
insert into #tmp_sp_help_alert exec msdb.dbo.sp_help_alert
create table #tmp_sp_help_alert
(id int null, name nvarchar(128) null, event_source nvarchar(100) null, event_category_id int null, event_id int null, message_id int null, severity int null, enabled tinyint null, delay_between_responses int null, last_occurrence_date int null, last_occurrence_time int null, last_response_date int null, last_response_time int null, notification_message nvarchar(512) null, include_event_description tinyint null, database_name nvarchar(128) null, event_description_keyword nvarchar(100) null, occurrence_count int null, count_reset_date int null, count_reset_time int null, job_id uniqueidentifier null, job_name nvarchar(128) null, has_notification int null, flags int null, performance_condition nvarchar(512) null, category_name nvarchar(128) null, wmi_namespace nvarchar(max) null, wmi_query nvarchar(max) null, type int null)
insert into #tmp_sp_help_alert exec msdb.dbo.sp_help_alert
drop table #tmp_sp_help_alert
tsha.idtsha.nameISNULL(tsha.event_source,N'')tsha.message_idtsha.severitytsha.enabledtsha.delay_between_responsesnulltsha.last_occurrence_datetsha.last_occurrence_timenulltsha.last_response_datetsha.last_response_timeISNULL(tsha.notification_message,N'')tsha.include_event_descriptionISNULL(tsha.database_name,N'')ISNULL(tsha.event_description_keyword,N'')tsha.occurrence_countnulltsha.count_reset_datetsha.count_reset_timeISNULL(tsha.job_id, convert(uniqueidentifier, N'00000000-0000-0000-0000-000000000000'))ISNULL(tsha.job_name,N'')tsha.has_notificationISNULL(tsha.performance_condition,N'')ISNULL(tsha.category_name,N'')ISNULL(tsha.wmi_namespace,N'')ISNULL(tsha.wmi_query,N'')tsha.typebkpms.media_set_idbkpms.media_uuidbkpms.media_family_countbkpms.namebkpms.descriptionbkpms.software_namebkpms.software_vendor_idbkpms.MTF_major_versionbkpmf.media_set_idbkpmf.media_family_idbkpmf.family_sequence_numberbkpmf.media_countbkpmf.logical_device_namebkpmf.physical_device_nameCASE WHEN bkpmf.device_type > 100 THEN bkpmf.device_type - 100 ELSE bkpmf.device_type ENDCASE WHEN bkpmf.device_type > 100 THEN 1 ELSE 0 ENDbkpmf.physical_block_sizebkpf.backup_set_idbkpf.first_family_numberbkpf.first_media_numberbkpf.filegroup_namebkpf.page_sizebkpf.file_numberbkpf.backed_up_page_countbkpf.file_typebkpf.source_file_block_sizebkpf.file_sizebkpf.logical_namebkpf.physical_drivebkpf.physical_namertsfg.restore_history_idrtsfg.filegroup_namertsf.restore_history_idrtsf.file_numberrtsf.destination_phys_drivertsf.destination_phys_namerthist.restore_history_idrthist.restore_daterthist.destination_database_namerthist.user_namerthist.backup_set_idCASE rthist.restore_type WHEN 'D' THEN 1 WHEN 'F' THEN 2 WHEN 'L' THEN 3 WHEN 'V' THEN 4 ENDrthist.replacerthist.recoveryrthist.restartrthist.stop_atrthist.device_countrthist.stop_at_mark_namerthist.stop_before
O
bkps.namebkps.backup_set_idbkps.backup_set_uuidbkps.media_set_idbkps.first_family_numberbkps.first_media_numberbkps.last_family_numberbkps.last_media_numberbkps.catalog_family_numberbkps.catalog_media_numberbkps.positionbkps.expiration_datebkps.software_vendor_idbkps.descriptionbkps.user_namebkps.software_major_versionbkps.software_minor_versionbkps.software_build_versionbkps.time_zonebkps.mtf_minor_versionbkps.first_lsnbkps.last_lsnbkps.checkpoint_lsnbkps.database_backup_lsnbkps.database_creation_datebkps.backup_start_datebkps.backup_finish_dateCASE bkps.type WHEN 'D' THEN 1 WHEN 'I' THEN 2 WHEN 'L' THEN 3 WHEN 'F' THEN 4 ENDbkps.sort_orderbkps.code_pagebkps.compatibility_levelbkps.database_versionbkps.backup_sizebkps.database_namebkps.server_namebkps.machine_namebkps.flagsbkps.unicode_localebkps.unicode_compare_stylebkps.collation_namebkps.is_password_protected
DECLARE @PageSize float
SELECT @PageSize=v.low/1024.0 FROM master..spt_values v WHERE v.number=1 AND v.type='E'
rtrim(s.name)s.fileidrtrim(s.filename)(s.size * @PageSize)case when s.maxsize=-1 then -1 else s.maxsize * @PageSize endCASE WHEN (0 <>(s.status & 0x100000)) THEN s.growth ELSE s.growth * @PageSize ENDCASE WHEN s.growth=0 THEN 99 WHEN (0 <>(s.status & 0x100000)) THEN 1 ELSE 0 ENDs.groupids.names.file_ids.physical_names.size * CONVERT(float,8)CASE when s.max_size=-1 then -1 else s.max_size * CONVERT(float,8) ENDCASE s.is_percent_growth WHEN 1 THEN s.growth ELSE s.growth*8 ENDCASE when s.growth=0 THEN 99 ELSE s.is_percent_growth ENDs.is_media_read_onlys.is_read_onlycase s.state when 6 then 1 else 0 ends.is_sparses.data_space_idNULLNULLNULLcreate table #tpdv ( Name nvarchar(512) NOT NULL)
insert #tpdv (Name) EXECUTE master.dbo.xp_get_tape_devices
drop table #tpdvNamev.number = l.mode AND v.type = N'L'v2.number = l.ltype AND v2.type = N'LR'
CREATE TABLE #t(spid int, mode int, dbid int NULL, objid int, objid2 int, indid int, status tinyint, ltype tinyint, objname sysname NULL, indname sysname NULL, dbname sysname NULL, sch sysname NULL)
INSERT #t SELECT spid = req_spid, mode = req_mode, dbid=rsc_dbid, objid=l.rsc_objid, objid2=l.rsc_objid, indid=l.rsc_indid, status = l.req_status, ltype = l.rsc_type, objname=NULL, indname=NULL, dbname = NULL, sch = NULL
FROM master.dbo.syslockinfo l WHERE rsc_dbid != db_id('tempdb') OR rsc_objid != object_id('#t')
update #t set dbname = d.name FROM #t t LEFT OUTER JOIN master.dbo.sysdatabases d ON d.dbid = t.dbid
update #t set dbname = d.name FROM #t t LEFT OUTER JOIN sys.databases d ON d.database_id = t.dbid
update #t set objid2 = -objid2 where dbname is null
DECLARE name_cursor CURSOR
FOR select t.dbid, t.dbname FROM #t t GROUP BY t.dbid, t.dbname
OPEN name_cursor
DECLARE @dbid int
DECLARE @dbname sysname
DECLARE @sql nvarchar(1000)
FETCH NEXT FROM name_cursor INTO @dbid, @dbname
WHILE (@@FETCH_STATUS <> -1)
BEGIN
IF (@@FETCH_STATUS <> -2)
BEGIN
SELECT @sql = 'use ' + quotename(@dbname) + ' update #t set objname = o.name, indname = i.name, sch=user_name(o.uid) FROM #t AS t '+
'LEFT JOIN dbo.sysobjects AS o ON o.id = t.objid LEFT OUTER JOIN dbo.sysindexes AS i ON i.id = t.objid AND i.indid = t.indid '+
'WHERE t.ltype in (4,5) AND t.dbid = ' + CAST(@dbid AS NVARCHAR(20))
IF( NOT @dbname IS NULL )--resource database
SELECT @sql = 'use ' + quotename(@dbname)
ELSE
SELECT @sql = ''
SELECT @sql = @sql + ' update #t set objname = o.name, indname = i.name, sch=schema_name(o.schema_id) FROM #t AS t '+
'LEFT JOIN sys.all_objects AS o ON o.object_id = t.objid2 LEFT OUTER JOIN sys.indexes AS i ON i.object_id = t.objid2 AND i.index_id = t.indid '+
'WHERE t.ltype in (4,5) AND t.dbid = ' + CAST(@dbid AS NVARCHAR(20))
EXEC(@sql)
END
FETCH NEXT FROM name_cursor INTO @dbid, @dbname
END
CLOSE name_cursor
DEALLOCATE name_cursor
drop table #t
l.spidv.namel.dbnamel.schl.objnamel.indnamel.status
d
r.session_id = p.session_idpr.spid = p.session_idp.spidp.spidsuser_sname(p.sid)p.hostnamep.statusp.cmddb_name(p.dbid)p.cpup.memusagep.blockedcase when p.spid < 51 then 1 else 0 endp.session_idp.session_idp.login_namep.host_namer.statusr.commanddb_name(r.database_id)p.cpu_timep.memory_usager.blocking_session_id~p.is_user_processp.program_name0p.ecidpr.ecid
create table #err_log_text_tmp_final(Text nvarchar(4000), ArchiveNo int null, LogDate datetime null, ProcessInfo nvarchar(100) null)
declare @text_offset int
declare @process_info_length int
set @text_offset = 34
set @process_info_length = 10
drop table #err_log_text_tmp_final
ert.LogDateert.ProcessInfoert.Textert.ArchiveNo
S
create table #err_log_tmp(ArchiveNo int, CreateDate nvarchar(24))
create table #err_log_tmp(ArchiveNo int, CreateDate nvarchar(24), Size int)
insert #err_log_tmp exec master.dbo.sp_enumerrorlogs
drop table #err_log_tmp
er.ArchiveNoer.ArchiveNoCONVERT(datetime, er.CreateDate, 101)er.Size
"
l.req_mode = v.number and v.type = N'L' and db_id() = l.rsc_dbid
l.req_spidv.namedb_name(l.rsc_dbid)object_name(l.rsc_objid)object_name(l.rsc_indid)l.req_status
r
cl.nameCOLLATIONPROPERTY(name, 'CodePage')COLLATIONPROPERTY(name, 'LCID')COLLATIONPROPERTY(name, 'ComparisonStyle')cl.description
0
(st.indid <> 0 and st.indid <> 255) and 0 = OBJECTPROPERTY(st.id,N'IsMSShipped')
st.namest.indidcase when (st.status & 16777216) <> 0 then 1 else 0 endSTATS_DATE(st.id, st.indid)1 - INDEXPROPERTY(st.id,st.name,N'IsStatistics')INDEXPROPERTY(st.id,st.name,N'IsAutoStatistics')''st.id6st.stats_idst.no_recomputeSTATS_DATE(st.object_id, st.stats_id)1 - INDEXPROPERTY(st.object_id,st.name,N'IsStatistics')st.auto_created''nullst.object_idst.name7
m
c.colidcase when c.number > 1 then c.number else 0 endc.textcast(c.id as nvarchar(20)) + N'_' + cast(db_id() as nvarchar(20)) + N'_' + cast(case when c.number > 1 then c.number else 0 end as nvarchar(20))c.id
+
cstr.xtype='D' and cstr.name not like N'#%%' and 0!=convert(bit,cstr.category & 0x0800)0N'CONSTRAINT'
Q
Q
OBJECTPROPERTY({0}.id,N'ExecIsAnsiNullsOn')OBJECTPROPERTY({0}.id,N'ExecIsQuotedIdentOn')OBJECTPROPERTY({0}.id, N'IsSchemaBound')(SELECT TOP 1 encrypted FROM dbo.syscomments p WHERE {0}.id = p.id AND p.colid=1 and p.number < 2){0}.status & 4cast({0}.id as nvarchar(20)) + '_' + cast(db_id() as nvarchar(20)) + '_0'CASE WHEN ISNULL({0}.definition, s{0}.definition) IS NULL THEN 1 ELSE 0 ENDISNULL({0}.is_recompiled, s{0}.is_recompiled)ISNULL({0}.definition, s{0}.definition)0t.tdefaultt.default_object_id
~
c.cdefaultc.default_object_idxproc.xtype='X'xproc.type='X'>
(o.status & 0x10) <> 0o.nameo.phynameo.cntrltypeo.status & 0x08st.xusertype = st.xtype or st.name=N'sysname'st.schema_id=4CASE WHEN st.name IN (N'decimal', N'numeric') THEN 1 ELSE 0 ENDCASE WHEN st.name IN ( N'varchar', N'varbinary', N'nvarchar' ) THEN 1 ELSE 0 ENDCASE WHEN st.name IN (N'decimal', N'int', N'numeric', N'smallint', N'tinyint', N'bigint') THEN 1 ELSE 0 ENDCASE WHEN st.name IN ( N'char', N'varchar', N'binary', N'varbinary', N'nchar', N'nvarchar' ) THEN 1 ELSE 0 ENDst.allownullsCASE WHEN st.name IN (N'char', N'varchar', N'binary', N'varbinary', N'nchar', N'nvarchar') THEN st.prec ELSE st.length ENDst.xprecst.xscaleISNULL(st.collation,N'')st.is_nullableCASE WHEN st.name IN (N'nchar', N'nvarchar') THEN st.max_length/2 ELSE st.max_length ENDISNULL(st.collation_name,N'')st.user_type_idst.precisionst.scale@@OPTIONS & 1@@OPTIONS & 2@@OPTIONS & 4@@OPTIONS & 8@@OPTIONS & 16@@OPTIONS & 32@@OPTIONS & 64@@OPTIONS & 128@@OPTIONS & 256@@OPTIONS & 512@@OPTIONS & 1024@@OPTIONS & 2048@@OPTIONS & 4096@@OPTIONS & 8192@@OPTIONS & 16384t.id = c.id and t.type = 'U't.object_id = c.object_idc.namet.nameuser_name(t.uid)c.xusertypeschema_name(t.schema_id)c.user_type_idparam.number = 1 or (param.number = 0 and 1 = OBJECTPROPERTY(param.id, N'IsScalarFunction') and isnull(param.name, '') != '')param.is_output = 0-1cstr.type=N'F'rfr.constid = cstr.idki.indid = rfr.rkeyindid AND ki.id = rfr.rkeyidrfr.rkeyid = rtbl.idki.index_id = cstr.key_index_id and ki.object_id = cstr.referenced_object_idrtbl.object_id = cstr.referenced_object_idki.namertbl.nameuser_name(rtbl.uid)OBJECTPROPERTY(cstr.id, N'CnstIsDeleteCascade')OBJECTPROPERTY(cstr.id, N'CnstIsUpdateCascade')ki.namertbl.nameschema_name(rtbl.schema_id)cstr.delete_referential_actioncstr.update_referential_actionst.xusertype != st.xtype and st.name != N'sysname'def.id = st.tdefaultrul.id = st.domainst.schema_id!=4 and st.system_type_id!=240 and st.user_type_id != st.system_type_iddef.object_id = st.default_object_idrul.object_id = st.rule_object_idst.xusertypest.user_type_idst.lengthst.allownullsst.variable(case when st.tdefault = 0 then N'' else def.name end)(case when st.tdefault = 0 then N'' else user_name(def.uid) end)(case when st.domain = 0 then N'' else rul.name end)(case when st.domain = 0 then N'' else user_name(rul.uid) end)N'TYPE'st.collationst.max_lengthst.is_nullable(case when st.default_object_id = 0 then N'' else def.name end)(case when st.default_object_id = 0 then N'' else schema_name(def.schema_id) end)(case when st.rule_object_id = 0 then N'' else rul.name end)(case when st.rule_object_id = 0 then N'' else schema_name(rul.schema_id) end)st.collation_nameCASE WHEN baset.name IN ( N'varchar', N'varbinary', N'nvarchar' ) THEN 1 ELSE 0 END6st.user_type_id0obj.xtype=N'D' and obj.name not like N'#%%' and 0=(obj.category & 0x0800)obj.type=N'D' and not(obj.parent_object_id > 0)N'DEFAULT'v.type = 'C ' and not cfg.status is null and v.number = cfg.config ucfg.config = cfg.configv.namev.numberv.lowv.highcfg.status & 1cfg.status & 2ucfg.valuecfg.valuecfg.commentcfg.namecfg.configuration_idcfg.minimumcfg.maximumcfg.is_dynamiccfg.is_advancedcfg.valuecfg.value_in_usecfg.descriptiont.domaint.rule_object_id
p
c.domainc.rule_object_id
j
obj.xtype=N'R'obj.type=N'R' and (0 = obj.parent_object_id or obj.parent_object_id is null)N'RULE'
f
create table #tmpntlogin ( [Account name] sysname NULL, Type sysname NULL, [Privilege] sysname NULL, [Mapped login name] sysname NULL, [Permission path] sysname NULL)
insert into #tmpntlogin exec master.dbo.xp_logininfo
drop table #tmpntlogin
[Account name]Type[Privilege][Mapped login name][Permission path]
drop table #tmpntgrp
t.namet.description 'Server[@Name=' + quotename(@@SERVERNAME,'''') + ']/Database[@Name=' + quotename(db_name(),'''') +
']/' + (case when (uob.sysstat & 0xf) = 0 then
'UserDefinedFunction'
when (uob.sysstat & 0xf) = 1 or (uob.sysstat & 0xf) = 3 then
'Table'
when (uob.sysstat & 0xf) = 2 then
'View'
when (uob.sysstat & 0xf) = 4 then
'StoredProcedure'
when (uob.sysstat & 0xf) = 6 then
'Default'
when (uob.sysstat & 0xf) = 7 then
'Rule'
when (uob.sysstat & 0xf) = 8 then
'Trigger'
when (uob.sysstat & 0xf) = 9 then
'PrimaryKey'
when (uob.sysstat & 0xf) = 10 then
'Check'
when (uob.sysstat & 0xf) = 11 then
'ForeignKey'
when (uob.sysstat & 0xf) = 12 then
'UserDefinedDataType'
else
'Unknown'
end) + '[@Name='+quotename(uob.name,'''')+']'
'Server[@Name=' + quotename(cast(serverproperty(N'Servername') as sysname),'''') + ']/Database[@Name=' + quotename(db_name(),'''') +
']/' + (case when (uob.sysstat & 0xf) = 0 then
'UserDefinedFunction'
when (uob.sysstat & 0xf) = 1 or (uob.sysstat & 0xf) = 3 then
'Table'
when (uob.sysstat & 0xf) = 2 then
'View'
when (uob.sysstat & 0xf) = 4 then
'StoredProcedure'
when (uob.sysstat & 0xf) = 6 then
'Default'
when (uob.sysstat & 0xf) = 7 then
'Rule'
when (uob.sysstat & 0xf) = 8 then
'Trigger'
when (uob.sysstat & 0xf) = 9 then
'PrimaryKey'
when (uob.sysstat & 0xf) = 10 then
'Check'
when (uob.sysstat & 0xf) = 11 then
'ForeignKey'
when (uob.sysstat & 0xf) = 12 then
'UserDefinedDataType'
else
'Unknown'
end) + '[@Name='+quotename(uob.name,'''')+']'
uob.nameuob.iduser_name(uob.uid)uob.crdate(uob.sysstat & 0xf)
/
u.uid = m.id
drop table #tmp_role_member_ids
u.principal_id = m.id
drop table #tmp_role_member_ids
u.nameu.uidsuser_sname(u.sid)(CASE
WHEN u.issqlrole = 1 THEN N'Role'
WHEN u.isapprole = 1 THEN N'ApplicationRole'
ELSE N'User' END)
m.role_idu.principal_idsuser_sname(u.sid)(CASE u.type
WHEN 'A' THEN N'ApplicationRole'
WHEN 'R' THEN N'Role'
ELSE N'User' END)
m.role_id
declare @Arg sysname
declare @Param sysname
declare @n int
select @n=0
select @Param='dummy'
create table #srvargs (value nvarchar(512) NOT NULL)
while(not @Param is null)
begin
select @Param=null
select @Arg='SqlArg'+convert(nvarchar,@n)
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer\Parameters', @Arg, @Param OUTPUT
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer\Parameters', @Arg, @Param OUTPUT
insert #srvargs select @Param where not @Param is null
select @n=@n+1
end
drop table #srvargs
arg.value
~
sv.category_id = tshc.category_idtsho_e.id = sv.notify_email_operator_idtsho_ns.id = sv.notify_netsend_operator_idtsho_p.id = sv.notify_page_operator_id
create table #tmp_sp_help_category
(category_id int null, category_type tinyint null, name nvarchar(128) null)
insert into #tmp_sp_help_category exec msdb.dbo.sp_help_category
create table #tmp_sp_help_operator
(id int null, name nvarchar(128) null, enabled tinyint null, email_address nvarchar(100) null, last_email_date int null, last_email_time int null, pager_address nvarchar(100) null, last_pager_date int null, last_pager_time int null, weekday_pager_start_time int null, weekday_pager_end_time int null, saturday_pager_start_time int null, saturday_pager_end_time int null, sunday_pager_start_time int null, sunday_pager_end_time int null, pager_days tinyint null, netsend_address nvarchar(100) null, last_netsend_date int null, last_netsend_time int null, category_name nvarchar(128) null)
insert into #tmp_sp_help_operator exec msdb.dbo.sp_help_operator
drop table #tmp_sp_help_operator
drop table #tmp_sp_help_category
sv.namesv.job_idsv.originating_serversv.enabledISNULL(sv.description,N'')sv.start_step_idISNULL(suser_sname(sv.owner_sid), N'')sv.notify_level_eventlogsv.notify_level_emailsv.notify_level_netsendsv.notify_level_pagesv.delete_levelsv.date_createdsv.date_modifiedsv.version_numbertshc.nameISNULL(tsho_e.name,N'')ISNULL(tsho_ns.name,N'')ISNULL(tsho_p.name,N'')sv.job_idnullnullnullnullnullnullnullnullnullnullnull
%
ik.id = clmns.id and 0 != ik.status & 0x0800cik.indid = ik.indid and cik.colid = clmns.colid and cik.id = clmns.idd.id = clmns.cdefault and 0=d.category & 0x0800r.id = clmns.domainic.object_id = clmns.object_id and ic.column_id = clmns.column_idcc.object_id = clmns.object_id and cc.column_id = clmns.column_idik.object_id = clmns.object_id and 1=ik.is_primary_keycik.index_id = ik.index_id and cik.column_id = clmns.column_id and cik.object_id = clmns.object_id and 0 = cik.is_included_columnd.object_id = clmns.default_object_idr.object_id = clmns.rule_object_idclmns.nameclmns.colidclmns.isnullableclmns.iscomputedISNULL(cik.colid, 0)COLUMNPROPERTY(clmns.id, clmns.name, N'UsesAnsiTrim')clmns.colstat & 2clmns.colstat & 8COLUMNPROPERTY(clmns.id, clmns.name, N'IsFulltextIndexed')cast(clmns.id as nvarchar(20)) + '_' + cast(clmns.colid as nvarchar(20)) + '_' + cast(db_id() as nvarchar(20)) + '_0'COLUMNPROPERTY(clmns.id, clmns.name, N'IsIdentity')ISNULL((select top 1 1 from dbo.sysforeignkeys AS colfk where colfk.fkey = clmns.colid and colfk.fkeyid = clmns.id), 0)ISNULL(clmns.collation, N'')clmns.cdefaultclmns.id(case when clmns.cdefault = 0 then N'' else d.name end)(case when clmns.cdefault = 0 then N'' else user_name(d.uid) end)(case when clmns.domain = 0 then N'' else r.name end)(case when clmns.domain = 0 then N'' else user_name(r.uid) end)N'COLUMN'clmns.nameclmns.column_idclmns.is_nullableclmns.is_computedISNULL(cik.index_column_id, 0)clmns.is_ansi_paddedclmns.is_rowguidcolISNULL(ic.is_not_for_replication, 0)COLUMNPROPERTY(clmns.object_id, clmns.name, N'IsFulltextIndexed')ISNULL(cc.definition,N'')ISNULL(cc.is_persisted, 0)ISNULL(clmns.collation_name, N'')ISNULL((select TOP 1 1 from sys.foreign_key_columns AS colfk where colfk.parent_column_id = clmns.column_id and colfk.parent_object_id = clmns.object_id), 0)clmns.is_identityISNULL(ic.seed_value,0)ISNULL(ic.increment_value,0)clmns.default_object_id(case when clmns.default_object_id = 0 then N'' when d.parent_object_id > 0 then N'' else d.name end)(case when clmns.default_object_id = 0 then N'' when d.parent_object_id > 0 then N'' else schema_name(d.schema_id) end)(case when clmns.rule_object_id = 0 then N'' else r.name end)(case when clmns.rule_object_id = 0 then N'' else schema_name(r.schema_id) end)1clmns.object_id
r
udf.xtype in ( 'TF', 'FN', 'IF') and udf.name not like N'#%%'ret_param.id = udf.id and ret_param.number = 0 and ret_param.name=''udf.type in ('TF', 'FN', 'IF', 'FS', 'FT')ret_param.object_id = udf.object_id and ret_param.is_output = 1OBJECTPROPERTY(udf.id, N'IsDeterministic')(case when 1 = OBJECTPROPERTY(udf.id, N'IsScalarFunction') then 1 when 1 = OBJECTPROPERTY(udf.id, N'IsInlineFunction') then 3 when 1 = OBJECTPROPERTY(udf.id, N'IsTableFunction') then 2 else 0 end)1N'FUNCTION'OBJECTPROPERTYEX(udf.object_id, N'IsDeterministic')(case when 'FN' = udf.type then 1 when 'FS' = udf.type then 1 when 'IF' = udf.type then 3 when 'TF' = udf.type then 2 when 'FT' = udf.type then 2 else 0 end)CASE WHEN udf.type IN ('FN','IF','TF') THEN 1 WHEN udf.type IN ('FS','FT') THEN 2 ELSE 1 ENDret_param.nametr.type = 'TR'tr.type in ('TR', 'TA')trr.object_id = tr.object_idtei.object_id = tr.object_id and tei.type=1teu.object_id = tr.object_id and teu.type=2ted.object_id = tr.object_id and ted.type=3mod.object_id = tr.object_idasmbl.assembly_id = mod.assembly_id1-OBJECTPROPERTY(tr.id,N'ExecIsTriggerDisabled')OBJECTPROPERTY(tr.id, N'ExecIsInsteadOfTrigger')OBJECTPROPERTY(tr.id,N'ExecIsInsertTrigger')CASE WHEN OBJECTPROPERTY(tr.id, N'ExecIsFirstInsertTrigger') = 1 THEN 0 WHEN OBJECTPROPERTY(tr.id, N'ExecIsLastInsertTrigger') = 1 THEN 2 ELSE 1 ENDOBJECTPROPERTY(tr.id,N'ExecIsUpdateTrigger')CASE WHEN OBJECTPROPERTY(tr.id, N'ExecIsFirstUpdateTrigger') = 1 THEN 0 WHEN OBJECTPROPERTY(tr.id, N'ExecIsLastUpdateTrigger') = 1 THEN 2 ELSE 1 ENDOBJECTPROPERTY(tr.id,N'ExecIsDeleteTrigger')CASE WHEN OBJECTPROPERTY(tr.id, N'ExecIsFirstDeleteTrigger') = 1 THEN 0 WHEN OBJECTPROPERTY(tr.id, N'ExecIsLastDeleteTrigger') = 1 THEN 2 ELSE 1 ENDOBJECTPROPERTY(tr.id,N'ExecIsTriggerNotForRepl')1N'TRIGGER'~trr.is_disabledtrr.is_instead_of_triggerISNULL(tei.object_id,0)CASE WHEN tei.is_first = 1 THEN 0 WHEN tei.is_last = 1 THEN 2 ELSE 1 ENDISNULL(teu.object_id,0)CASE WHEN teu.is_first = 1 THEN 0 WHEN teu.is_last = 1 THEN 2 ELSE 1 ENDISNULL(ted.object_id,0)CASE WHEN ted.is_first = 1 THEN 0 WHEN ted.is_last = 1 THEN 2 ELSE 1 ENDtrr.is_not_for_replicationCASE WHEN tr.type = N'TR' THEN 1 WHEN tr.type = N'TA' THEN 2 ELSE 1 ENDcstr.type = 'C'
a
@@SERVERNAMEserverproperty(N'Servername')ISNULL(serverproperty(N'instancename'),N'')
declare @command nvarchar(300)
select @command = 'dbcc checkprimaryfile (N''' + @fileName + ''' , 3)'
create table #SmoPrimayChildren(status INT,fileid INT,name sysname,filename nvarchar(512))
insert #SmoPrimayChildren exec (@command)
drop table #SmoPrimayChildren
s.names.fileidcase when (s.status & 0x40) = 0 then 1 else 0 endRTRIM(s.filename)
"
drop table #OLEDBProvProp
prop.Nameprop.IDprop.Descriptionprop.Flags
1
create table #OLEDBProv ( Name sysname NOT NULL, ParseName sysname NOT
NULL,Description sysname NOT NULL ) insert #OLEDBProv EXECUTE master.dbo.xp_enum_oledb_providers drop table #OLEDBProvOLEDBProviderop.Nameop.ParseNameop.Description
d
declare @command nvarchar(300)
select @command = 'dbcc checkprimaryfile (N'''+ @fileName + ''' , 2)'
create table #smoPrimaryFileProp(property sql_variant NULL, value sql_variant NULL)
insert #smoPrimaryFileProp exec (@command)
drop table #smoPrimaryFileProprtrim(@fileName)p.propertyp.value
p
sjs.namesjs.schedule_idsjs.date_createdconvert(bit,sjs.enabled)sjs.freq_typesjs.freq_intervalsjs.freq_subday_typesjs.freq_subday_intervalsjs.freq_relative_intervalsjs.freq_recurrence_factorsjs.active_start_datecast(null as datetime)sjs.active_start_time0sjs.active_end_datecast(null as datetime)sjs.active_end_time0(SELECT COUNT(*) FROM msdb.dbo.sysjobschedules as js WHERE (js.schedule_id = sjs.schedule_id))
create table #tmp_sp_help_schedule
(schedule_id int null, schedule_uid uniqueidentifier null, schedule_name nvarchar(128) null, enabled int null, freq_type int null, freq_interval int null, freq_subday_type int null, freq_subday_interval int null, freq_relative_interval int null, freq_recurrence_factor int null, active_start_date int null, active_end_date int null, active_start_time int null, active_end_time int null, date_created datetime null, schedule_description nvarchar(4000) null, job_count int null)
insert into #tmp_sp_help_schedule exec msdb.dbo.sp_help_schedule
drop table #tmp_sp_help_schedule
tshs.schedule_nametshs.schedule_idtshs.date_createdtshs.enabledtshs.freq_typetshs.freq_intervaltshs.freq_subday_typetshs.freq_subday_intervaltshs.freq_relative_intervaltshs.freq_recurrence_factornulltshs.active_start_date0tshs.active_start_time0tshs.active_end_timenulltshs.active_end_datetshs.job_count
drop table #tmp_sp_help_jobschedule
tshj.schedule_nametshj.schedule_idtshj.date_createdtshj.enabledtshj.freq_typetshj.freq_intervaltshj.freq_subday_typetshj.freq_subday_intervaltshj.freq_relative_intervaltshj.freq_recurrence_factornulltshj.active_start_date0tshj.active_start_time0tshj.active_end_timenulltshj.active_end_datetshj.job_id(SELECT COUNT(*) FROM msdb.dbo.sysjobschedules as js WHERE (js.schedule_id = tshj.schedule_id))tshj.job_count
drop table #jobstep_outputlog_tmp
tjsol.job_idtjsol.job_nametjsol.step_idtjsol.step_nametjsol.step_uidtjsol.date_createdtjsol.date_modifiedtjsol.log_sizetjsol.logsp.proxy_id = tshj.proxy_id
create table #tmp_sp_help_proxy
(proxy_id int null, name nvarchar(300) null, credential_identity nvarchar(300) null, enabled tinyint null, description nvarchar(max) null, user_sid binary(200) null, credential_id int null, credential_identity_exists int null)
insert into #tmp_sp_help_proxy(proxy_id, name, credential_identity, enabled, description, user_sid, credential_id, credential_identity_exists)
exec msdb.dbo.sp_help_proxy
drop table #tmp_sp_help_proxy
drop table #tmp_sp_help_jobstep
tshj.step_nametshj.step_idCASE LOWER(tshj.subsystem) when 'tsql' THEN 1 WHEN 'activescripting' THEN 2 WHEN 'cmdexec' THEN 3
WHEN 'snapshot' THEN 4 WHEN 'logreader' THEN 5 WHEN 'distribution' THEN 6
WHEN 'merge' THEN 7 WHEN 'queuereader' THEN 8 WHEN 'analysisquery' THEN 9
WHEN 'analysiscommand' THEN 10 WHEN 'dts' THEN 11 WHEN 'ssis' THEN 11 ELSE 0 ENDISNULL(tshj.command,N'')ISNULL(tshj.command,N'')tshj.cmdexec_success_codetshj.on_success_actiontshj.on_success_step_idtshj.on_fail_actiontshj.on_fail_step_idISNULL(tshj.server,N'')ISNULL(tshj.database_name,N'')ISNULL(tshj.database_user_name,N'')tshj.retry_attemptstshj.retry_intervaltshj.os_run_priorityISNULL(tshj.output_file_name,N'')tshj.last_run_outcometshj.last_run_durationtshj.last_run_retriesnulltshj.last_run_datetshj.last_run_timetshj.flagsISNULL(sp.name,N'')tshj.job_idclmns.id = ic.id and clmns.colid = ic.colid and clmns.number = 0ic.column_id > 0 and (ic.key_ordinal > 0 or ic.partition_ordinal = 0)clmns.object_id = ic.object_id and clmns.column_id = ic.column_idclmns.nameic.keynoic.idic.indidCOLUMNPROPERTY(ic.id, clmns.name, N'IsComputed')INDEXKEY_PROPERTY(ic.id, ic.indid, ic.keyno, N'IsDescending')clmns.name(case ic.key_ordinal when 0 then cast(1 as tinyint) else ic.key_ordinal end)ic.object_idic.index_idCOLUMNPROPERTY(ic.object_id, clmns.name, N'IsComputed')ic.is_descending_keyic.is_included_column
L$
i.indid > 0 and i.indid < 255 and 1 != INDEXPROPERTY(i.id,i.name,N'IsStatistics') and 1 != INDEXPROPERTY(i.id,i.name,N'IsHypothetical')k.parent_obj = i.id AND k.name = i.name AND k.xtype IN (N'PK', N'UQ')i.index_id > 0 and i.is_hypothetical = 0s.stats_id = i.index_id AND s.object_id = i.object_idk.parent_object_id = i.object_id AND k.unique_index_id = i.index_idxi.object_id = i.object_id AND xi.index_id = i.index_idxi2.object_id = xi.object_id AND xi2.index_id = xi.using_xml_index_iddeclare @PageSize float select @PageSize=v.low/1024.0 from master.dbo.spt_values v where v.number=1 and v.type='E'i.namei.indidOBJECTPROPERTY(i.id,N'IsMSShipped')INDEXPROPERTY(i.id,i.name,N'IsFulltextKey')CASE WHEN (i.status & 0x1000000) <> 0 THEN 1 ELSE 0 ENDINDEXPROPERTY(i.id,i.name,N'IndexFillFactor')CASE WHEN (i.indid = 1) THEN (i.used - i.dpages - ISNULL((SELECT
SUM(j.used) FROM dbo.sysindexes AS j WHERE (j.indid > 1) AND (j.indid < 255) AND (j.id = i.id) AND (j.name = i.name)), 0)) * @PageSize ELSE i.used * @PageSize ENDCASE i.indid WHEN 1 THEN 1 ELSE 0 ENDCASE WHEN 0 != i.status&0x800 THEN 1 WHEN 0 != i.status&0x1000 THEN 2 ELSE 0 ENDi.status&2CASE WHEN 0 != (i.status&0x01) THEN 1 ELSE 0 ENDINDEXPROPERTY(i.id, i.name, N'IsRowLockDisallowed')INDEXPROPERTY(i.id, i.name, N'IsPageLockDisallowed')INDEXPROPERTY(i.id, i.name, N'IsPadIndex')ISNULL(k.status & 4, 0)i.idk.idi.indidi.namei.index_idOBJECTPROPERTY(i.object_id,N'IsMSShipped')INDEXPROPERTY(i.object_id,i.name,N'IsFulltextKey')s.no_recomputei.fill_factorISNULL((select @PageSize * SUM(a.used_pages - CASE WHEN a.type <> 1 THEN a.used_pages WHEN p.index_id < 2 THEN a.data_pages ELSE 0 END)
FROM sys.partitions as p
JOIN sys.allocation_units as a ON a.container_id = p.partition_id
WHERE p.object_id = i.object_id AND p.index_id = i.index_id),0.0)CASE i.index_id WHEN 1 THEN 1 ELSE 0 ENDi.is_primary_key + 2*i.is_unique_constrainti.is_uniquei.ignore_dup_key~i.allow_row_locks~i.allow_page_locksINDEXPROPERTY(i.object_id, i.name, N'IsPadIndex')i.is_disabledcase when i.type=3 then 1 else 0 endcase UPPER(ISNULL(xi.secondary_type,'')) when 'P' then 1 when 'V' then 2 when 'R' then 3 else 0 endISNULL(xi2.name, N'')ISNULL(k.is_system_named, 0)i.object_idk.object_idi.index_idi.object_id
)
create table #tmp_sp_get_sqlagent_properties
(auto_start int null, msx_server_name sysname null, sqlagent_type int null, startup_account nvarchar(255) null, sqlserver_restart int null, jobhistory_max_rows int null, jobhistory_max_rows_per_job int null, errorlog_file nvarchar(255) null, errorlogging_level int null, error_recipient nvarchar(30) null, monitor_autostart int null, local_host_server sysname null, job_shutdown_timeout int null, cmdexec_account varbinary(64) null, regular_connections int null, host_login_name nvarchar(128) null, host_login_password varbinary(512) null, login_timeout int null, idle_cpu_percent int null, idle_cpu_duration int null, oem_errorlog int null, sysadmin_only int null, email_profile nvarchar(64) null, email_save_in_sent_folder int null, cpu_poller_enabled int null)
insert into #tmp_sp_get_sqlagent_properties(auto_start, msx_server_name, sqlagent_type, startup_account, sqlserver_restart, jobhistory_max_rows, jobhistory_max_rows_per_job, errorlog_file, errorlogging_level, error_recipient, monitor_autostart, local_host_server, job_shutdown_timeout, cmdexec_account, regular_connections, host_login_name, host_login_password, login_timeout, idle_cpu_percent, idle_cpu_duration, oem_errorlog, sysadmin_only, email_profile, email_save_in_sent_folder, cpu_poller_enabled)
exec msdb.dbo.sp_get_sqlagent_properties
create table #tmpMsxAccountName ( domain nvarchar(255) null, username nvarchar(255) null)
if ( ( (@@microsoftversion / power(2, 24) = 8) and (@@microsoftversion & 0xffff >= 760) ) or (@@microsoftversion / power(2, 24) > 8))
begin
insert into #tmpMsxAccountName(domain, username) exec master.dbo.xp_sqlagent_msx_account N'GET'
end
create table #tmp_sp_get_sqlagent_properties
(auto_start int null, msx_server_name sysname null, sqlagent_type int null, startup_account nvarchar(255) null, sqlserver_restart int null, jobhistory_max_rows int null, jobhistory_max_rows_per_job int null, errorlog_file nvarchar(255) null, errorlogging_level int null, error_recipient nvarchar(30) null, monitor_autostart int null, local_host_server sysname null, job_shutdown_timeout int null, cmdexec_account varbinary(64) null, regular_connections int null, host_login_name nvarchar(128) null, host_login_password varbinary(512) null, login_timeout int null, idle_cpu_percent int null, idle_cpu_duration int null, oem_errorlog int null, sysadmin_only int null, email_profile nvarchar(64) null, email_save_in_sent_folder int null, cpu_poller_enabled int null, replace_alert_tokens_enabled int null)
insert into #tmp_sp_get_sqlagent_properties(auto_start, msx_server_name, sqlagent_type, startup_account, sqlserver_restart, jobhistory_max_rows, jobhistory_max_rows_per_job, errorlog_file, errorlogging_level, error_recipient, monitor_autostart, local_host_server, job_shutdown_timeout, cmdexec_account, regular_connections, host_login_name, host_login_password, login_timeout, idle_cpu_percent, idle_cpu_duration, oem_errorlog, sysadmin_only, email_profile, email_save_in_sent_folder, cpu_poller_enabled, replace_alert_tokens_enabled)
exec msdb.dbo.sp_get_sqlagent_properties
create table #tmpMsxAccountName
(msx_connection int null, msx_credential_id int null, msx_credential_name nvarchar(300) null, msx_login_name nvarchar(300) null)
insert into #tmpMsxAccountName(msx_connection, msx_credential_id, msx_credential_name, msx_login_name)
exec msdb.dbo.sp_msx_get_account
declare @DatabaseMailProfile nvarchar(255)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'DatabaseMailProfile', @param = @DatabaseMailProfile OUT, @no_output = N'no_output'
declare @AgentMailType int
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent', N'UseDatabaseMail', @param = @AgentMailType OUT, @no_output = N'no_output'
drop table #tmp_sp_get_sqlagent_properties
drop table #tmpMsxAccountName
@@SERVERNAMEserverproperty(N'Servername')ISNULL(tsgsp.msx_server_name,N'')tsgsp.sqlagent_typetsgsp.sqlserver_restarttsgsp.monitor_autostarttsgsp.jobhistory_max_rowstsgsp.jobhistory_max_rows_per_jobtsgsp.errorlog_filetsgsp.errorlogging_levelISNULL(tsgsp.error_recipient,N'')tsgsp.job_shutdown_timeoutISNULL(tsgsp.email_profile,N'')tsgsp.email_save_in_sent_foldertsgsp.oem_errorlogtsgsp.cpu_poller_enabledtsgsp.idle_cpu_percenttsgsp.idle_cpu_durationtsgsp.login_timeoutISNULL(tsgsp.host_login_name,N'')ISNULL(tsgsp.local_host_server,N'')tsgsp.auto_startISNULL((select top 1 ISNULL(domain + N'\', N'') + username as [UserName] from #tmpMsxAccountName),N'')tsgsp.sysadmin_onlytsgsp.replace_alert_tokens_enabledISNULL((select top 1 msx_login_name from #tmpMsxAccountName),N'')ISNULL((select top 1 msx_credential_name from #tmpMsxAccountName),N'')ISNULL(@DatabaseMailProfile,N'')ISNULL(@AgentMailType, 0)1
c
create table #SmoMemberTemp
(
role_col sysname NOT NULL,
mem_col sysname NOT NULL,
id_col varbinary(85)
)
insert into #SmoMemberTemp (role_col, mem_col, id_col) exec master.dbo.sp_helpsrvrolemember
drop table #SmoMemberTemp
p.principal_id = m.member_principal_id
lgnmb.mem_colp.name
lnklgn.ishqoutmap = 1
lnklgn.sid=xlnklgn.sid and ISNULL(xlnklgn.ishqoutmap,0) = 0ll.local_principal_id = sp.principal_idLinkedServerLoginISNULL(xlnklgn.name, '')ISNULL(lnklgn.name, N'')convert(bit,lnklgn.selfoutmap)lnklgn.srvidISNULL(sp.name, '')ISNULL(ll.remote_name, N'')ll.uses_self_credentialll.server_idll.modify_datesp.xtype = N'P' OR sp.xtype = N'RF'sp.type = N'P' OR sp.type = N'RF' OR sp.type='PC'spp.object_id = sp.object_id OBJECTPROPERTY(sp.id, N'ExecIsStartup')CASE sp.xtype WHEN N'RF' THEN 1 ELSE 0 END1N'PROCEDURE'ISNULL(spp.is_auto_executed,0)CASE sp.type WHEN N'RF' THEN 1 ELSE 0 ENDCASE WHEN sp.type = N'P' THEN 1 WHEN sp.type = N'PC' THEN 2 ELSE 1 ENDv.type = 'V'v.type = 'V'0OBJECTPROPERTY(v.id, 'TableFullTextCatalogId')N'VIEW'v.has_opaque_metadata(tbl.type='U' or tbl.type='S')idx.id = tbl.id and idx.indid < 2idx.object_id = tbl.object_id and idx.index_id < 2tbl.lob_data_space_id = dstext.data_space_id
declare @PageSize float
select @PageSize=v.low/1024.0 from master.dbo.spt_values v where v.number=1 and v.type='E'
CASE WHEN (OBJECTPROPERTY(tbl.id, N'tableisfake')=1) THEN 1 ELSE 0 END@PageSize*((SELECT sum(sidx.dpages)
FROM dbo.sysindexes sidx
WHERE sidx.indid < 2 and sidx.id = tbl.id)
+
(SELECT isnull(sum(sidx.used), 0)
FROM dbo.sysindexes sidx
WHERE sidx.indid = 255 and sidx.id = tbl.id))@PageSize*(SELECT sum(isnull(sidx.used,0)-isnull(sidx.dpages,0))
FROM dbo.sysindexes sidx
WHERE sidx.indid < 2 and sidx.id = tbl.id)CASE idx.indid WHEN 1 THEN 1 ELSE 0 ENDISNULL((SELECT top 1 s.groupname FROM dbo.sysfilegroups s, dbo.sysindexes i WHERE i.id = tbl.id and i.indid in (0,1)AND i.groupid = s.groupid), N'')tbl.replinfoOBJECTPROPERTY(tbl.id, 'TableFullTextCatalogId')idx.indididx.rowsOBJECTPROPERTY(tbl.id,N'IsAnsiNullsOn')OBJECTPROPERTY(tbl.id,N'IsQuotedIdentOn')idx.rowcntN'TABLE'CASE idx.index_id WHEN 1 THEN 1 ELSE 0 ENDISNULL(dstext.name,N'')tbl.is_replicatedISNULL( ( select sum (spart.rows) from sys.partitions spart where spart.object_id = tbl.object_id and spart.index_id < 2), 0)tbl.uses_ansi_nullsOBJECTPROPERTY(tbl.object_id,N'IsQuotedIdentOn')0ISNULL((select @PageSize * SUM(CASE WHEN a.type <> 1 THEN a.used_pages WHEN p.index_id < 2 THEN a.data_pages ELSE 0 END)
FROM sys.indexes as i
JOIN sys.partitions as p ON p.object_id = i.object_id and p.index_id = i.index_id
JOIN sys.allocation_units as a ON a.container_id = p.partition_id
where i.object_id = tbl.object_id),0.0)ISNULL((select @PageSize * SUM(a.used_pages - CASE WHEN a.type <> 1 THEN a.used_pages WHEN p.index_id < 2 THEN a.data_pages ELSE 0 END)
FROM sys.indexes as i
JOIN sys.partitions as p ON p.object_id = i.object_id and p.index_id = i.index_id
JOIN sys.allocation_units as a ON a.container_id = p.partition_id
where i.object_id = tbl.object_id),0.0)idx.index_idtbl.object_id
\!
srv.srvid != 0srv.srvid != 0 AND srv.srvname = so.srvnamesrv.server_id != 0
create table #tmp_srvoptions([srvname] nvarchar(255) not null, [collationcompatible] bit not null, [dataaccess] bit not null, [dist] bit not null, [dpub] bit not null, [pub] bit not null, [rpc] bit not null, [rpcout] bit not null, [sub] bit not null)
declare @srvname nvarchar(255)
declare @collation_compatible bit
declare @data_access bit
declare @dist bit
declare @pub bit
declare @dpub bit
declare @rpc bit
declare @rpc_out bit
declare @sub bit
create table #tmp(opt nvarchar(100))
declare srvname_cursor cursor for
select srvname FROM dbo.sysservers WHERE srvid <> 0
open srvname_cursor
fetch next from srvname_cursor into @srvname
while @@FETCH_STATUS = 0
begin
truncate table #tmp
insert #tmp exec sp_serveroption @srvname
set @collation_compatible = case when exists ( select * from #tmp where opt = 'collation compatible') then 1 else 0 end
set @data_access = case when exists ( select * from #tmp where opt = 'data access') then 1 else 0 end
set @dist = case when exists ( select * from #tmp where opt = 'dist') then 1 else 0 end
set @dpub = case when exists ( select * from #tmp where opt = 'dpub') then 1 else 0 end
set @pub = case when exists ( select * from #tmp where opt = 'pub') then 1 else 0 end
set @rpc = case when exists ( select * from #tmp where opt = 'rpc') then 1 else 0 end
set @rpc_out = case when exists ( select * from #tmp where opt = 'rpc out') then 1 else 0 end
set @sub = case when exists ( select * from #tmp where opt = 'sub') then 1 else 0 end
insert into #tmp_srvoptions([srvname], [collationcompatible], [dataaccess], [dist], [dpub], [pub], [rpc], [rpcout], [sub]) values (@srvname, @collation_compatible, @data_access, @dist, @dpub, @pub, @rpc, @rpc_out, @sub)
fetch next from srvname_cursor into @srvname
end
close srvname_cursor
deallocate srvname_cursor
drop table #tmp
drop table #tmp_srvoptions
srv.srvnamesrv.srvidISNULL(srv.catalog,N'')ISNULL(srv.datasource,N'')ISNULL(srv.location,N'')srv.srvproductsrv.providernamesrv.providerstringnullso.collationcompatibleso.dataaccessso.distso.dpubso.pubso.rpcso.rpcoutso.subsrv.collationcompatiblesrv.dataaccesssrv.distsrv.dpubsrv.pubsrv.rpcsrv.rpcoutsrv.subISNULL(COLLATIONPROPERTYFROMID(srv.srvcollation, 'name'),N'')srv.connecttimeoutsrv.lazyschemavalidationsrv.querytimeoutsrv.useremotecollationsrv.namesrv.server_idISNULL(srv.catalog,N'')ISNULL(srv.data_source,N'')ISNULL(srv.location,N'')srv.productsrv.providersrv.is_collation_compatiblesrv.is_data_access_enabledsrv.is_distributor0srv.is_publishersrv.is_remote_login_enabledsrv.is_rpc_out_enabledsrv.is_subscriberISNULL(srv.collation_name,N'')srv.connect_timeoutsrv.lazy_schema_validationsrv.query_timeoutsrv.uses_remote_collationsrv.modify_datesrv.provider_stringnullLanguage s.name s.langid s.dateformat s.alias s.days s.datefirst s.months s.shortmonths s.upgrade s.lcid s.msglangid
create table #filetmpfin (Name nvarchar(255) NOT NULL, IsFile bit NULL)
if(@Name is null)
begin
create table #filetmp (Name nvarchar(255) NOT NULL, depth int NOT NULL, IsFile bit NULL )
insert #filetmp EXECUTE master.dbo.xp_dirtree @Path, 1, 1
insert #filetmpfin select Name, IsFile from #filetmp f
drop table #filetmp
end
if(NOT @Name is null)
begin
declare @FullName nvarchar(300)
if(@Path is null)
select @FullName = @Name
else
select @FullName = @Path + '\' + @Name
create table #filetmp2 ( Exist bit NOT NULL, IsDir bit NOT NULL, DirExist bit NULL )
insert #filetmp2 EXECUTE master.dbo.xp_fileexist @FullName
insert #filetmpfin select @Name, 1-IsDir from #filetmp2 where Exist = 1 or IsDir = 1 drop table #filetmp2
end
drop table #filetmpfinName@Path+'\'+Name@PathIsFile
create table #fixdrv ( Name sysname NOT NULL, Size int NOT NULL, Type sysname NULL )
insert #fixdrv (Name, Size) EXECUTE master.dbo.xp_fixeddrives
update #fixdrv set Type = 'Fixed' where Type IS NULL
insert #fixdrv (Name, Size) EXECUTE master.dbo.xp_fixeddrives 1
update #fixdrv set Type = 'Remote' where Type IS NULL
insert #fixdrv (Name, Size) EXECUTE master.dbo.xp_fixeddrives 2
update #fixdrv set Type = 'Removable' where Type IS NULL
insert #fixdrv (Name, Size) EXECUTE master.dbo.xp_fixeddrives 3
update #fixdrv set Type = 'CD-ROM' where Type IS NULL
update #fixdrv set Name = Name + ':'
drop table #fixdrv
NameSizeType
\
create table #cdromdrv ( Name sysname NOT NULL, Size int NOT NULL ) insert #cdromdrv EXECUTE master.dbo.xp_fixeddrives 3
update #cdromdrv set Name = Name + ':'
drop table #cdromdrvNameSize
2
create table #fixdrv ( Name sysname NOT NULL, Size int NOT NULL ) insert #fixdrv EXECUTE master.dbo.xp_fixeddrives 2
update #fixdrv set Name = Name + ':'
drop table #fixdrvNameSize
0
create table #fixdrv ( Name sysname NOT NULL, Size int NOT NULL ) insert #fixdrv EXECUTE master.dbo.xp_fixeddrives 1
update #fixdrv set Name = Name + ':'
drop table #fixdrvNameSize
-
create table #fixdrv ( Name sysname NOT NULL, Size int NOT NULL ) insert #fixdrv EXECUTE master.dbo.xp_fixeddrives
update #fixdrv set Name = Name + ':'
drop table #fixdrvNameSize
i
rl.isapprole = 1rl.type = 'A'rl.namerl.uidrl.createdaterl.updatedate2rl.principal_idrl.default_schema_namerl.create_daterl.modify_date40
4
rl.issqlrole = 1ou.uid = rl.altuidrl.type = 'R'ou.principal_id = rl.owning_principal_idrl.namerl.uidrl.createdaterl.updatedate2rl.principal_idrl.create_daterl.modify_date4ou.name0((u.issqlrole != 1 and u.isapprole != 1 ) or (u.sid=0x00)) and u.isaliased != 1 and u.hasdbaccess != 0u.type in ('U', 'S', 'G', 'C', 'K')dp.grantee_principal_id = u.principal_id and dp.type = N'CO'cert.sid = u.sidak.sid = u.sidu.nameu.uidISNULL(suser_sname(u.sid),N'')CASE WHEN u.uid = 1 OR u.uid = 16382 OR u.uid = 16383 THEN 1 ELSE 0 ENDCASE WHEN 0 <> u.isntuser THEN 0 WHEN 0 <> u.isntgroup THEN 1 ELSE 2 END0u.sidu.hasdbaccessu.createdateu.updatedateN'USER'u.principal_idISNULL(suser_sname(u.sid),N'')CASE WHEN u.principal_id < 5 OR u.principal_id = 16382 OR u.principal_id = 16383 THEN 1 ELSE 0 ENDCASE WHEN N'U' = u.type THEN 0 WHEN N'G' = u.type THEN 1 WHEN N'S' = u.type THEN 2 WHEN N'C' = u.type THEN 3 WHEN N'K' = u.type THEN 4 ENDCASE dp.state WHEN N'G' THEN 1 WHEN 'W' THEN 1 ELSE 0 ENDu.sidCASE WHEN N'C' = u.type THEN 1 WHEN N'K' = u.type THEN 2 WHEN N'S' = u.type AND suser_sname(u.sid) IS NULL THEN 3 ELSE 0 ENDISNULL(cert.name,N'')ISNULL(ak.name,N'')u.create_dateu.modify_dateISNULL(u.default_schema_name,N'')40
W
create table #loginmappings( LoginName sysname NULL, DBName sysname NULL, UserName sysname NULL, AliasName sysname NULL )
declare @db_name nvarchar(512)
declare crs cursor local fast_forward
for ( select name from master.dbo.sysdatabases where 1 = has_dbaccess(name))
for ( select name from sys.databases where 1 = has_dbaccess(name))
open crs
fetch crs into @db_name
while @@fetch_status >= 0
begin
set @db_name = quotename(@db_name)
exec('use ' + @db_name + ' INSERT #loginmappings select suser_sname(u.sid), db_name(), u.name, null from dbo.sysusers u where suser_sname(u.sid) is not null')
exec('use ' + @db_name + ' INSERT #loginmappings select suser_sname(u.sid), db_name(), u.name, null from sys.database_principals AS u where suser_sname(u.sid) is not null')
fetch crs into @db_name
end
close crs
deallocate crs
drop table #loginmappings
logmap.LoginNamelogmap.DBNamelogmap.UserNamelog.language = l.namelog.type in ('U', 'G', 'S', 'C', 'K') AND log.principal_id not between 101 and 255 AND log.name <> N'##MS_AgentSigningCertificate##'l.name = log.default_language_namesqllog.principal_id = log.principal_idsp.grantee_principal_id = log.principal_id and sp.type = N'COSQ'c.credential_id = log.credential_idcert.sid = log.sidak.sid = log.sidlog.loginnameISNULL(log.language, N'')l.aliaslog.dbnamelog.denyloginCASE WHEN 0 <> log.isntuser THEN 0 WHEN 0 <> log.isntgroup THEN 1 ELSE 2 ENDCASE WHEN (0 = log.isntuser AND 0 = log.isntgroup) THEN 99 WHEN (0 = log.denylogin and 0 = log.hasaccess) THEN 0 WHEN (0 = log.denylogin ) THEN 1 ELSE 2 ENDlog.hasaccesslog.sidlog.createdatelog.updatedateCASE log.sid WHEN 0x01 THEN 1 ELSE 0 ENDlog.nameISNULL(log.default_language_name,N'')l.aliaslog.default_database_nameCASE sp.state WHEN N'D' THEN 1 ELSE 0 ENDCASE WHEN N'U' = log.type THEN 0 WHEN N'G' = log.type THEN 1 WHEN N'S' = log.type THEN 2 WHEN N'C' = log.type THEN 3 WHEN N'K' = log.type THEN 4 ENDCASE WHEN (N'U' != log.type AND N'G' != log.type) THEN 99 WHEN (sp.state is null) THEN 0 WHEN (N'G'=sp.state) THEN 1 ELSE 2 ENDCASE WHEN (sp.state is null) THEN 0 ELSE 1 ENDlog.sidsqllog.is_policy_checkedsqllog.is_expiration_checkedlog.create_datelog.modify_dateLOGINPROPERTY(log.name, N'IsLocked')LOGINPROPERTY(log.name, N'IsExpired')LOGINPROPERTY(log.name, N'IsMustChange')log.principal_idISNULL(c.name,N'')ISNULL(cert.name,N'')ISNULL(ak.name,N'')log.is_disabled101CASE WHEN log.principal_id < 256 THEN 1 ELSE 0 END
'
v1.low=0 and v1.type='SRV'
r.type ='R' and r.name != N'public'
v1.name = r.name and v1.low = 0
Rolev1.namev2.namev1.numberr.namer.principal_idN''v1.number101
j
s.groupid = 0s.type = 1 and s.database_id = db_id()
tspclog.DatabaseName = db_name()
create table #tmplogspc (DatabaseName sysname, LogSize float, SpaceUsedPerc float, Status bit)
insert #tmplogspc EXEC ('dbcc sqlperf(logspace)')
drop table #tmplogspc
tspclog.LogSize * tspclog.SpaceUsedPerc * 10.24
u
s.type = 0 and s.database_id = db_id() and (s.drop_lsn IS NULL)
create table #tmpspc (Fileid int, FileGroup int, TotalExtents int, UsedExtents int, Name sysname, FileName nchar(520))
insert #tmpspc EXEC ('dbcc showfilestats')
drop table #tmpspc
FILEPROPERTY(s.name, N'IsPrimaryFile')tspc.UsedExtents*convert(float,64)(tspc.TotalExtents - tspc.UsedExtents)*convert(float,64)declare @PageSize float select @PageSize=v.low/1024.0 from master..spt_values v
where v.number=1 and v.type='E'
g.groupnameg.groupidg.status & 0x08g.status & 0x10ISNULL((select sum(s.size * @PageSize) from dbo.sysfiles s where s.groupid = g.groupid), 0)cast(g.name as varbinary(256))g.data_space_idg.is_read_onlyg.is_defaultISNULL((select sum(gs.size)*convert(float,8) from sys.database_files gs where gs.data_space_id = g.data_space_id), 0)
=
t.dbname = dtb.name
create table #tmplog (dbname sysname null, log_size float null, log_space_used float null, status int)
INSERT INTO #tmplog EXEC ('DBCC SQLPERF(LOGSPACE)')
drop table #tmplog
df.database_id = dtb.database_id and 1=df.data_space_id and 1 = df.file_iddmi.database_id = dtb.database_iddrs.database_id = dtb.database_iddtb.namedtb.dbidsuser_sname(dtb.sid)dtb.crdatertrim(dtb.filename)NULLt.log_size*(100-t.log_space_used)*10.24NULLNULL0(select count(*) from master.dbo.sysprocesses p where dtb.dbid=p.dbid)dtb.cmptlevel''dtb.category(select top 1 fg.groupname from dbo.sysfilegroups as fg where fg.status & 0x10 <> 0 )case when dtb.name in ('master','model','msdb','tempdb') then 1 else category & 16 enddtb.namedtb.database_idsuser_sname(dtb.owner_sid)dtb.create_datenull00000(select count(*) from master.dbo.sysprocesses p where dtb.database_id=p.dbid)dtb.compatibility_level''dtb.is_published*1+dtb.is_subscribed*2+dtb.is_merge_published*4dtb.service_broker_guiddtb.is_fulltext_enableddtb.collation_nameISNULL((select top 1 ftc.name from sys.fulltext_catalogs as ftc where ftc.is_default=1),N'')(select top 1 ds.name from sys.data_spaces as ds where ds.is_default=1)0isnull(dtb.source_database_id, 0)(select count(1) from sys.databases dtbmir where dtbmir.source_database_id = dtb.database_id)ISNULL(DB_NAME(dtb.source_database_id), N'')dmi.mirroring_partner_namedmi.mirroring_rolecoalesce(dmi.mirroring_safety_level + 1, 0)coalesce(dmi.mirroring_state + 1, 0)dmi.mirroring_witness_namecoalesce(dmi.mirroring_witness_state + 1, 0)case when dmi.mirroring_partner_name is null then 0 else 1 enddmi.mirroring_guiddmi.mirroring_role_sequencedmi.mirroring_safety_sequencedmi.mirroring_failover_lsndtb.log_reuse_wait
case
when DATABASEPROPERTY(dtb.name,'IsShutDown') is null then 0x200
else 0
end |
case
when 1 = dtb.is_in_standby then 0x40
else 0
end |
case
when 1 = dtb.is_cleanly_shutdown then 0x80
else 0
end |
case dtb.state
when 1 then 0x2
when 2 then 0x8
when 3 then 0x4
when 4 then 0x10
when 5 then 0x100
when 6 then 0x20
else 1
end
drs.recovery_fork_guiddrs.database_guiddtb.is_auto_create_stats_ondtb.is_auto_update_stats_oncase when dtb.name in ('master','model','msdb','tempdb') then 1 else dtb.is_distributor endDATABASEPROPERTYEX(dtb.name, 'IsFulltextEnabled')DATABASEPROPERTYEX(dtb.name, 'Collation')
case
-- if all these are false then we are in the Normal state
-- except some return NULL if it's AutoClosed
when (DATABASEPROPERTY(dtb.name,'IsInLoad') = 0 and
(DATABASEPROPERTY(dtb.name,'IsInRecovery') = 0 or DATABASEPROPERTY(dtb.name,'IsInRecovery') is null) and
(DATABASEPROPERTY(dtb.name,'IsNotRecovered') = 0 or DATABASEPROPERTY(dtb.name,'IsNotRecovered') is null) and
DATABASEPROPERTY(dtb.name,'IsSuspect') = 0 and
DATABASEPROPERTY(dtb.name,'IsOffline') = 0 and
DATABASEPROPERTY(dtb.name,'IsInStandBy') = 0 and
(DATABASEPROPERTY(dtb.name,'IsShutDown') = 0 or DATABASEPROPERTY(dtb.name,'IsShutDown') is null) and
DATABASEPROPERTY(dtb.name,'IsEmergencyMode') = 0) then 1
else 0
end |
case
when DATABASEPROPERTY(dtb.name,'IsInLoad') = 1 then 2
else 0
end |
case
when DATABASEPROPERTY(dtb.name,'IsInRecovery') = 1 and
DATABASEPROPERTY(dtb.name,'IsNotRecovered') = 1 then 4
else 0
end |
case
when DATABASEPROPERTY(dtb.name,'IsInRecovery') = 1 then 8
else 0
end |
case
when DATABASEPROPERTY(dtb.name,'IsSuspect') = 1 then 16
else 0
end |
case
when DATABASEPROPERTY(dtb.name,'IsOffline') = 1 then 32
else 0
end |
case
when DATABASEPROPERTY(dtb.name,'IsInStandBy') = 1 then 64
else 0
end |
case
when DATABASEPROPERTY(dtb.name,'IsShutDown') = 1 then 128
when DATABASEPROPERTY(dtb.name,'IsShutDown') is null then (512 + 128)
else 0
end |
case
when DATABASEPROPERTY(dtb.name,'IsEmergencyMode') = 1 then 256
else 0
end
( case LOWER(convert( nvarchar(128), DATABASEPROPERTYEX(dtb.name, 'Updateability'))) when 'read_write' then 1 else 0 end)DATABASEPROPERTYEX(dtb.name, 'Version')CHARINDEX(N'_CS_', CAST(DATABASEPROPERTYEX(dtb.name, 'Collation') AS nvarchar(255)))DATABASEPROPERTY(dtb.name,'IsFulltextEnabled')000000000''dtb.namedtb.namehas_dbaccess(dtb.name)(select max(backup_finish_date) from msdb..backupset where type = 'L' and database_name = dtb.name)(select max(backup_finish_date) from msdb..backupset where type = 'D' and database_name = dtb.name)000
i lSystem.Resources.ResourceReader, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089#System.Resources.RuntimeResourceSet PADPADPÉdl
dǬ4H
!L~G긄ѿr\ŕ\⯯E݆}X/l
hkj:3ra7jc0VPh+qm6x{ 7 8 e B S E R v \ + @C o u l d N o t G e t I n f o F r o m D e p e n d e n c y R o w ,C o u l d N o t I n s t a n t i a t e O b j ( 6D a t a b a s e N a m e M u s t B e S p e c i f i e d F FD a t a b a s e N a m e M u s t B e S p e c i f i e d i n T h e U r n f *E n u m O b j e c t T a g N o t F o u n d "F a i l e d T o C r e a t e U r n (F a i l e d T o L o a d A s s e m b l y &F