I have a method (old legacy code) that suddenly started taking much longer time to execute. The only thing that has changed is that I've upgraded from SQL Server 2008 R2 Expr to SQL Server 2014 Expr and therefore started using SMO 2014.
I have a large number of databases, around 180, that I run through to try to find a number of them. The code that runs through them looks like this.
foreach (Database db in instance.Databases)
{
foreach (FileGroup fileGroup in db.FileGroups)
{
foreach (DataFile dataFile in fileGroup.Files)
{
}
}
}
When I find the database I'm looking for the second foreach suddely takes a lot longer to execute, in worst cases up to a minute.
There is no code executing between the second and third foreach.
The code within the third foreach, where I do my stuff, executes fast as usual.
I cant figure out why this is taking so much longer. I've tried to find out if anything has changed in SMO in SQL Server 2014 that could cause this but I've had no luck.
If anyone could give me some idea about where to look I'd appreciate it.
* UPDATE *
This is the query made by SMO 2014 that, according to SQL Profiler, takes time. This query is not made when using SMO 2008 R2
exec sp_executesql N'SELECT
ISNULL((case dmi.mirroring_redo_queue_type when N''UNLIMITED'' then 0 else
dmi.mirroring_redo_queue end),0) AS [MirroringRedoQueueMaxSize],
ISNULL(dmi.mirroring_connection_timeout,0) AS [MirroringTimeout],
ISNULL(dmi.mirroring_partner_name,'''') AS [MirroringPartner],
ISNULL(dmi.mirroring_partner_instance,'''') AS [MirroringPartnerInstance],
ISNULL(dmi.mirroring_role,0) AS [MirroringRole],
ISNULL(dmi.mirroring_safety_level + 1, 0) AS [MirroringSafetyLevel],
ISNULL(dmi.mirroring_state + 1, 0) AS [MirroringStatus],
ISNULL(dmi.mirroring_witness_name,'''') AS [MirroringWitness],
ISNULL(dmi.mirroring_witness_state + 1, 0) AS [MirroringWitnessStatus],
CAST(case when dmi.mirroring_partner_name is null then 0 else 1 end AS bit)
AS [IsMirroringEnabled],
ISNULL(dmi.mirroring_guid,''00000000-0000-0000-0000-0000000000000000'') AS
[MirroringID],
ISNULL(dmi.mirroring_role_sequence,0) AS [MirroringRoleSequence],
ISNULL(dmi.mirroring_safety_sequence,0) AS [MirroringSafetySequence],
ISNULL(dmi.mirroring_failover_lsn,0) AS
[MirroringFailoverLogSequenceNumber],
dtb.is_ansi_null_default_on AS [AnsiNullDefault],
dtb.is_ansi_nulls_on AS [AnsiNullsEnabled],
dtb.is_ansi_padding_on AS [AnsiPaddingEnabled],
dtb.is_ansi_warnings_on AS [AnsiWarningsEnabled],
dtb.is_arithabort_on AS [ArithmeticAbortEnabled],
dtb.is_auto_shrink_on AS [AutoShrink],
dtb.is_cursor_close_on_commit_on AS [CloseCursorsOnCommitEnabled],
dtb.is_concat_null_yields_null_on AS [ConcatenateNullYieldsNull],
dtb.is_numeric_roundabort_on AS [NumericRoundAbortEnabled],
dtb.is_quoted_identifier_on AS [QuotedIdentifiersEnabled],
dtb.is_read_only AS [ReadOnly],
dtb.is_recursive_triggers_on AS [RecursiveTriggersEnabled],
dtb.is_local_cursor_default AS [LocalCursorsDefault],
dtb.page_verify_option AS [PageVerify],
dtb.recovery_model AS [RecoveryModel],
dtb.user_access AS [UserAccess],
dtb.is_db_chaining_on AS [DatabaseOwnershipChaining],
dtb.is_auto_update_stats_async_on AS [AutoUpdateStatisticsAsync],
dtb.is_date_correlation_on AS [DateCorrelationOptimization],
dtb.is_trustworthy_on AS [Trustworthy],
dtb.name AS [Name],
dtb.database_id AS [ID],
dtb.create_date AS [CreateDate],
dtb.is_auto_create_stats_on AS [AutoCreateStatisticsEnabled],
dtb.is_auto_update_stats_on AS [AutoUpdateStatisticsEnabled],
dtb.is_parameterization_forced AS [IsParameterizationForced],
dtb.is_read_committed_snapshot_on AS [IsReadCommittedSnapshotOn],
dtb.is_auto_close_on AS [AutoClose],
dtb.is_broker_enabled AS [BrokerEnabled],
CAST(isnull(dtb.source_database_id, 0) AS bit) AS [IsDatabaseSnapshot],
ISNULL(DB_NAME(dtb.source_database_id), N'''') AS
[DatabaseSnapshotBaseName],
dtb.is_fulltext_enabled AS [IsFullTextEnabled],
dtb.service_broker_guid AS [ServiceBrokerGuid],
dtb.snapshot_isolation_state AS [SnapshotIsolationState],
(dtb.is_published*1+dtb.is_subscribed*2+dtb.is_merge_published*4) AS
[ReplicationOptions],
ISNULL(suser_sname(dtb.owner_sid),'''') AS [Owner],
ISNULL(dtb.log_reuse_wait,0) AS [LogReuseWaitStatus],
drs.recovery_fork_guid AS [RecoveryForkGuid],
drs.database_guid AS [DatabaseGuid],
CAST((case when drs.last_log_backup_lsn is not null then 1 else 0 end) AS
bit) AS [HasFullBackup],
CAST(case when dtb.name in (''master'',''model'',''msdb'',''tempdb'') then 1
else dtb.is_distributor end AS bit) AS [IsSystemObject],
CAST(case when ctb.database_id is null then 0 else 1 end AS bit) AS
[ChangeTrackingEnabled],
CAST(ISNULL(ctb.is_auto_cleanup_on,0) AS bit) AS
[ChangeTrackingAutoCleanUp],
ISNULL(ctb.retention_period,0) AS [ChangeTrackingRetentionPeriod],
CAST(ISNULL(ctb.retention_period_units,0) AS tinyint) AS
[ChangeTrackingRetentionPeriodUnits],
dtb.containment AS [ContainmentType],
dtb.default_language_lcid AS [DefaultLanguageLcid],
dtb.default_language_name AS [DefaultLanguageName],
dtb.default_fulltext_language_lcid AS [DefaultFullTextLanguageLcid],
ISNULL(dtb.default_fulltext_language_name,N'''') AS
[DefaultFullTextLanguageName],
CAST(dtb.is_nested_triggers_on AS bit) AS [NestedTriggersEnabled],
CAST(dtb.is_transform_noise_words_on AS bit) AS [TransformNoiseWords],
dtb.two_digit_year_cutoff AS [TwoDigitYearCutoff],
dtb.target_recovery_time_in_seconds AS [TargetRecoveryTime],
dtb.delayed_durability AS [DelayedDurability],
dtb.is_auto_create_stats_incremental_on AS
[AutoCreateIncrementalStatisticsEnabled],
case
when dtb.collation_name is null then 0x200
else 0
end |
case
when 1 = dtb.is_in_standby then 0x40
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
AS [Status],
CAST(( case LOWER(convert( nvarchar(128), DATABASEPROPERTYEX(dtb.name,
''Updateability''))) when ''read_write'' then 1 else 0 end) AS bit) AS
[IsUpdateable],
CAST(dtb.is_encrypted AS bit) AS [EncryptionEnabled],
CAST(dtb.is_honor_broker_priority_on AS bit) AS [HonorBrokerPriority],
CAST(has_dbaccess(dtb.name) AS bit) AS [IsAccessible],
ISNULL(fsopt.directory_name , N'''') AS [FilestreamDirectoryName],
ISNULL(fsopt.non_transacted_access , 0) AS [FilestreamNonTransactedAccess],
dtb.name AS [DatabaseName2],
dtb.containment AS [ContainmentType2]
FROM
master.sys.databases AS dtb
LEFT OUTER JOIN sys.database_mirroring AS dmi ON dmi.database_id =
dtb.database_id
LEFT OUTER JOIN sys.database_recovery_status AS drs ON drs.database_id =
dtb.database_id
LEFT OUTER JOIN sys.change_tracking_databases AS ctb ON ctb.database_id =
dtb.database_id
LEFT OUTER JOIN sys.database_filestream_options AS fsopt ON
fsopt.database_id = dtb.database_id
WHERE
(dtb.name=#_msparam_0)',N'#_msparam_0 nvarchar(4000)',#_msparam_0=N'2016-11-
03'
Is this query something that has been added to SMO 2014?
Does anyone have an idea about why this is run?
Related
I am using EF Core for my .NET Core 2.1 project to interact with Azure SQL Server.
I have query which fetches around 1.5L rows by joining multiple tables. It's taking a long time to return the result and it is getting timed out (more than 30 seconds). So I am going with pagination using skip and take.
So my final call looks like
query.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList();
This call works absolutely fine and give the expected results.
But when I add order by clause to this query:
query.OrderBy(sortField)
.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList()
Below is the generated SQL
SELECT [p].[Id], [p].[CreatedById], [p].[CreatedOn], [p].[CurrencyId], [p].[CustomerId], [p].[DataMigrationLogId], [p].[FollowUp], [p].[IsActive], [p].[ProjectName], [p].[PlantCode], [p].[ShipToDistanceFromPlant], [p].[StatusId],
[p].[UpdatedById], [p].[UpdatedOn], [p.DataMigrationLog].[Id], [p.DataMigrationLog].[CreatedOn], [p.DataMigrationLog].[GeneratedOn], [p.DataMigrationLog].[HasEdsBid], [p.DataMigrationLog].[HasMbiBid], [p.DataMigrationLog].[Log],
[p.DataMigrationLog].[RequestXml], [p.DataMigrationLog].[Status], [p.DataMigrationLog].[Xq1ProjectId], [p.UpdatedBy].[Id], [p.UpdatedBy].[CellPhone], [p.UpdatedBy].[CreatedOn], [p.UpdatedBy].[Discriminator], [p.UpdatedBy].[Email],
[p.UpdatedBy].[FirstName], [p.UpdatedBy].[HasAccessToDoors], [p.UpdatedBy].[HasAccessToWindows], [p.UpdatedBy].[IsActive], [p.UpdatedBy].[LastName], [p.UpdatedBy].[Prefix], [p.UpdatedBy].[RecentProjectId], [p.UpdatedBy].[UpdatedOn],
[p.UpdatedBy].[WorkPhone], [p.UpdatedBy].[XQ1LoginName], [p.UpdatedBy].[IsSuperAdmin], [p.UpdatedBy].[HasAccessToRestrictedReports], [p.UpdatedBy].[HasEdsProgramAndDealerPriceAccess], [p.UpdatedBy].[IsIss],
[p.UpdatedBy].[ProjectVisibilityId], [p.UpdatedBy].[CustomerId], [p.UpdatedBy].[IsApiUser], [p.CreatedBy].[Id], [p.CreatedBy].[CellPhone], [p.CreatedBy].[CreatedOn], [p.CreatedBy].[Discriminator], [p.CreatedBy].[Email],
[p.CreatedBy].[FirstName], [p.CreatedBy].[HasAccessToDoors], [p.CreatedBy].[HasAccessToWindows], [p.CreatedBy].[IsActive], [p.CreatedBy].[LastName], [p.CreatedBy].[Prefix], [p.CreatedBy].[RecentProjectId], [p.CreatedBy].[UpdatedOn],
[p.CreatedBy].[WorkPhone], [p.CreatedBy].[XQ1LoginName], [p.CreatedBy].[IsSuperAdmin], [p.CreatedBy].[HasAccessToRestrictedReports], [p.CreatedBy].[HasEdsProgramAndDealerPriceAccess], [p.CreatedBy].[IsIss],
[p.CreatedBy].[ProjectVisibilityId], [p.CreatedBy].[CustomerId], [p.CreatedBy].[IsApiUser], [p.Status].[Id], [p.Status].[Code], [p.Status].[Name], [p.Customer].[Id], [p.Customer].[AxCustomerNumber], [p.Customer].[CreatedById],
[p.Customer].[CreatedOn], [p.Customer].[CreditTermId], [p.Customer].[CurrencyId], [p.Customer].[CustomerTypeId], [p.Customer].[DefaultPricing], [p.Customer].[FabricSystemFreight], [p.Customer].[IsActive], [p.Customer].[IsSpecialFreight],
[p.Customer].[LocalityRepId], [p.Customer].[MinFreightCharge], [p.Customer].[CompanyName], [p.Customer].[Notes], [p.Customer].[PrimaryBusinessId], [p.Customer].[ProgramAccountId], [p.Customer].[Prospect],
[p.Customer].[ShippingDollarsThreshold], [p.Customer].[ShippingMilesThreshold], [p.Customer].[SpecialNote], [p.Customer].[SpecialPlantInstruction], [p.Customer].[UpdatedById], [p.Customer].[UpdatedOn],
[p.Customer].[Xq1ProgGroupName], [p.Customer].[Xq1SrNo], [p.Customer].[XqCustomerNumber], [p.Customer.ProgramAccount].[Id], [p.Customer.ProgramAccount].[AxCustomerNumber], [p.Customer.ProgramAccount].[CreatedById],
[p.Customer.ProgramAccount].[CreatedOn], [p.Customer.ProgramAccount].[CreditTermId], [p.Customer.ProgramAccount].[CurrencyId], [p.Customer.ProgramAccount].[CustomerTypeId], [p.Customer.ProgramAccount].[DefaultPricing],
[p.Customer.ProgramAccount].[FabricSystemFreight], [p.Customer.ProgramAccount].[IsActive], [p.Customer.ProgramAccount].[IsSpecialFreight], [p.Customer.ProgramAccount].[LocalityRepId], [p.Customer.ProgramAccount].[MinFreightCharge],
[p.Customer.ProgramAccount].[CompanyName], [p.Customer.ProgramAccount].[Notes], [p.Customer.ProgramAccount].[PrimaryBusinessId], [p.Customer.ProgramAccount].[ProgramAccountId], [p.Customer.ProgramAccount].[Prospect],
[p.Customer.ProgramAccount].[ShippingDollarsThreshold], [p.Customer.ProgramAccount].[ShippingMilesThreshold], [p.Customer.ProgramAccount].[SpecialNote], [p.Customer.ProgramAccount].[SpecialPlantInstruction],
[p.Customer.ProgramAccount].[UpdatedById], [p.Customer.ProgramAccount].[UpdatedOn], [p.Customer.ProgramAccount].[Xq1ProgGroupName], [p.Customer.ProgramAccount].[Xq1SrNo], [p.Customer.ProgramAccount].[XqCustomerNumber],
[p.Customer.CustomerType].[Id], [p.Customer.CustomerType].[Code], [p.Customer.CustomerType].[Name]
FROM [Projects] AS [p]
LEFT JOIN [DataMigrationLogs] AS [p.DataMigrationLog] ON [p].[DataMigrationLogId] = [p.DataMigrationLog].[Id]
INNER JOIN [Security].[XQUsers] AS [p.UpdatedBy] ON [p].[UpdatedById] = [p.UpdatedBy].[Id]
INNER JOIN [Security].[XQUsers] AS [p.CreatedBy] ON [p].[CreatedById] = [p.CreatedBy].[Id]
INNER JOIN [ProjectStatuses] AS [p.Status] ON [p].[StatusId] = [p.Status].[Id]
LEFT JOIN [Customers] AS [p.Customer] ON [p].[CustomerId] = [p.Customer].[Id]
LEFT JOIN (
SELECT [p.Customer.LocalityRep].*
FROM [Security].[XQUsers] AS [p.Customer.LocalityRep]
WHERE [p.Customer.LocalityRep].[Discriminator] = N'SALES_SP'
) AS [t] ON [p.Customer].[LocalityRepId] = [t].[Id]
LEFT JOIN [Customers] AS [p.Customer.ProgramAccount] ON [p.Customer].[ProgramAccountId] = [p.Customer.ProgramAccount].[Id]
LEFT JOIN (
SELECT [p.Customer.ProgramAccount.LocalityRep].*
FROM [Security].[XQUsers] AS [p.Customer.ProgramAccount.LocalityRep]
WHERE [p.Customer.ProgramAccount.LocalityRep].[Discriminator] = N'SALES_SP'
) AS [t0] ON [p.Customer.ProgramAccount].[LocalityRepId] = [t0].[Id]
LEFT JOIN [CustomerTypes] AS [p.Customer.CustomerType] ON [p.Customer].[CustomerTypeId] = [p.Customer.CustomerType].[Id]
WHERE ([p.UpdatedBy].[Discriminator] IN (N'INT_SYSADMMIN', N'XqInternalUser', N'EXT', N'SALES_SP', N'XqUser') AND [p.CreatedBy].[Discriminator] IN (N'INT_SYSADMMIN', N'XqInternalUser', N'EXT', N'SALES_SP', N'XqUser')) AND (EXISTS (
SELECT 1
FROM [Security].[BusinessUserRegions] AS [r]
WHERE [r].[RegionId] IN (CAST(6 AS bigint), CAST(8 AS bigint), CAST(9 AS bigint)) AND ([t].[Id] = [r].[BusinessUserId])) OR ([p.Customer].[ProgramAccountId] IS NOT NULL AND EXISTS (
SELECT 1
FROM [Security].[BusinessUserRegions] AS [r0]
WHERE [r0].[RegionId] IN (CAST(6 AS bigint), CAST(8 AS bigint), CAST(9 AS bigint)) AND ([t0].[Id] = [r0].[BusinessUserId]))))
ORDER BY [p].[CreatedOn]
It takes more than 30 seconds to execute and Azure SQL Server has query timeout of maximum 30 second, so it results in exception
System.Data.SqlClient.SqlException (0x80131904): Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
From my layman's understanding about SQL I think SQL us fetching the entire dataset for sorting and then trying to do pagination and hence it's taking more than 30 seconds. Please correct me if I am wrong.
I need to sort the result in query in self otherwise it will not provide the desired result set.
Is their any way to deal with this situation.
Any help is highly appreciated.
I have a query which fetches records from 7 tables. All these tables are JOINed to get the details, few tables used multiple times with different ON clause. So there are 10 JOINs in the query. How can we optimize the query for getting better performance? We already have indexes on JOIN columns. Anything we can do to reduce the number of JOINs? Am using MS SQL 2012 with compatibility level 2008.
Query:
SELECT TOP 100
MT.ProjectId,
matRef,
matDescription,
matKeyDescription,
matOpenDate,
matUFN,
matBranchRef,
matClosedDate,
ERN1.feeRef,
WorkTypeCode,
DPT.deptNo AS matDeptRef,
PreviousRef,
MT.ApplicationID,
MatterCompleted,
CASE WHEN MLC.PFCivil_MatterCount = 0 THEN 0 ELSE 1 END AS IsCPF,
CASE WHEN MLC.PF_MatterCount = 0 THEN 0 ELSE 1 END AS IsPF,
CASE WHEN MLC.Family_MatterCount = 0 THEN 0 ELSE 1 END AS IsFM,
CASE WHEN MLC.WL_MatterCount = 0 THEN 0 ELSE 1 END AS IsWills,
CASE WHEN MLC.Convey_MatterCount = 0 THEN 0 ELSE 1 END AS IsConvey,
CASE WHEN MLC.Probate_MatterCount = 0 THEN 0 ELSE 1 END AS IsProbate,
CASE WHEN MLC.PI_MatterCount = 0 THEN 0 ELSE 1 END AS IsPi,
CASE WHEN MLC.PIPortal_MatterCount = 0 THEN 0 ELSE 1 END AS IsPiPortal,
CASE WHEN MLC.CM_MatterCount = 0 THEN 0 ELSE 1 END AS IsChest,
CASE WHEN MLC.Campaigns_MatterCount = 0 THEN 0 ELSE 1 END AS IsMarketing,
CASE WHEN MLC.PFFamilyFixedFee_MatterCount = 0 THEN 0 ELSE 1 END AS IsPFFamilyFixedFeeMatter,
ERN2.feeRef AS MatPartner,
MatPFCertificateNo,
CASE WHEN MT.matClosedDate = {d''1753-01-01''} THEN 0 ELSE 1 END AS IsArchived,
'''' Modules,
MT.ChargeDescID,
MT.MatterTypeID,
PrimaryClient.ClientName,
MB.LastAccDate,
MB.LastBillDate,
MB.LastClientDate,
MB.LastTimeDate
FROM dbo.Matter AS MT
JOIN dbo.Departments AS DPT ON DPT.deptID = MT.deptID
JOIN dbo.Earners AS ERN1 ON ERN1.MemberId = MT.MatFeeMemId
JOIN dbo.Earners AS ERN2 ON ERN2.MemberId = MT.matPartnerMemId
JOIN dbo.WorkTypes AS WT ON WT.WorkTypeID = MT.WorkTypeID
JOIN dbo.ivw_MatterLinkCount AS MLC ON MLC.ProjectId = MT.ProjectId
JOIN dbo.Banks AS ClientBank ON MT.matClientBank = ClientBank.bankID
JOIN dbo.Banks AS OfficeBank ON MT.matOfficeBank = OfficeBank.bankID
JOIN dbo.Banks AS DepositBank ON MT.matDepositBank = DepositBank.bankID
JOIN uvw_MatterPrimaryClient AS PrimaryClient ON PrimaryClient.ProjectId = MT.ProjectId
JOIN dbo.MatterBalance AS MB ON MT.ProjectId = MB.ProjectID
WHERE matDescription LIKE #Description
ORDER BY Isarchived, matRef
The trick here is that 'WHERE matDescription LIKE #Description' is not the real filter.
The real filter is 'TOP 100' together with 'ORDER BY Isarchived, matRef' because this filter will absolutely filter out anything but 100 rows.
So you need an index at Isarchived, matRef too. Table scan for matRef probably delays this one.
Also unless the Isarchived, matRef combination is unique by constraint, you better add the PK at the end like ORDER BY Isarchived, matRef, matid so there would be no extra problem picking the top 100.
Finally, if Isarchived is something like 0/1 and you have tons of records with 0 value it is useless at order by as there would always be 0. Set it as a filter Isarchived = 0 and remove it from order by - use matRef, matid and add a single index to matRef only.
SQL Server 2012, Amazon RDS
This is my simple query
update [dbo].[DeliveryPlan]
set [Amount] = dp.Amount +
case when #useAmountColumn = 1 and dbo.ConvertToInt(bs.Amount) > 0
then dbo.ConvertToInt(bs.Amount)
else #amount
end
from
BaseSpecification bs
join
BaseSpecificationStatusType t on (StatusTypeID = t.StatusTypeID)
join
[DeliveryPlan] dp on (dp.BaseSpecificationID = bs.BaseSpecificationID and dp.ItemID = #itemID)
where
bs.BaseID = 130 and t.IsActive = 1
It can't be finished. If where condition bs.BaseID=130 (update 7000 rows) change for bs.BaseID=3 (update 1000000 rows) it lasts 13 sec.
Statistics are actual, I think
In performance monitor I see 5% processor usage
When I use sp to watch active connections and for this query
tempdb_allocations is 32, tembdb_current - 32, reads - 32 000 000, cpu - 860 000 (query lasts 20 minutes)
What is the problem?
UPDATE: I added non-clustered index for [DeliveryPlan] - by BaseSpecificationID + ItemID and problem is gone. Unfortunately I see this problem every day with different queries. And problem disappears unpredicatedly.
This will perform better and in a different way as the join conditions will narrow down the number of rows in the first go itself, rather than waiting for the where clause to execute. The execution plan will be different for both (with where/ without where).
UPDATE dp
SET Amount = dp.Amount + CASE
WHEN #useAmountColumn = 1
AND dbo.ConvertToInt( bs.Amount ) > 0 THEN dbo.ConvertToInt( bs.Amount )
ELSE #amount
END
FROM BaseSpecification bs
JOIN BaseSpecificationStatusType t ON
( bs.StatusTypeID = t.StatusTypeID
AND bs.BaseID = 130
AND t.IsActive = 1
)
JOIN DeliveryPlan dp ON
( dp.BaseSpecificationID = bs.BaseSpecificationID
AND dp.ItemID = #itemID
);
You may suffer from a locking condition for your base tables.
Optimize your query to update dp directly to avoid update all rows of DeliveryPlan
update dp set [Amount] = dp.Amount +
case
when #useAmountColumn=1 and dbo.ConvertToInt(bs.Amount)>0 then
dbo.ConvertToInt(bs.Amount)
else #amount
end
from
BaseSpecification bs
join BaseSpecificationStatusType t on (bs.StatusTypeID = t.StatusTypeID)
join [DeliveryPlan] dp on (dp.BaseSpecificationID = bs.BaseSpecificationID)
where
bs.BaseID = 130
and t.IsActive = 1
and dp.ItemID = #itemID
If the problem mentioned in the update part is that it comes and goes randomly, it sounds like bad parameter sniffing. When the problem happens you could look into plan cache to check if the query plan looks ok and in case it doesn't, what are the values the plan was created with (you can find them in the leftmost object in the plan) and for example use sp_recompile and see what kind of plan you'll get the next time.
I have a query very slow and I want to optimize it. I've created index on fields for the joins. My query is this:
SELECT DISTINCT
--a.row_id FK_SERVIZIO,
--CLI_UNICO.FK_CLIENTE FK_CLIENTE,
CLI.CDC_FISCALE CDC_FISCALE,
--com.descrizione
--CASE WHEN conc.COMUNE IS NOT NULL THEN 1 ELSE 0 END FL_OFFERTABILITA_GAS
CASE WHEN exists (select 1 from STG.T_STG_NBA_DT_S_ASSET_G a where a.owner_accnt_id=CLI.IDC_CLIENTE_CRM_KEY and status_cd in ('ATTIVATO'))
THEN 'SI' ELSE 'NO' END FLC_COMUNE_TERR
FROM STG.T_STG_NBA_DT_S_ASSET_G A,
STG.T_STG_PSP_DT_LISTA_COMUNI_TERR terr,
STG.T_STG_NBA_DT_R2DG_COMUNI_G com,
STG.T_STG_NBA_DT_S_ADDR_PER_G ind_for,
--STG.V_DML_NBA_SITO q,
ODS.T_ODS_CRM_DT_CLIENTI_CRM CLI,--ODS.V_ODS_NBA_DT_ASS_CLI_CLIUNICO CLI_UNICO,
STG.T_STG_NBA_DT_S_ORG_EXT_G cforn
--STG.T_STG_NBA_DT_R2DG_CONCESS_G conc,
WHERE
--CLI.IDC_CLIENTE_CRM_KEY=A.OWNER_ACCNT_ID
terr.LDS_DESCRIZIONE_COMUNE=com.DESCRIZIONE
AND com.CODICE_ISTAT=ind_for.x_cod_istat
AND ind_for.row_id = cforn.PR_ADDR_ID
and cforn.row_id=A.serv_acct_id
i put index on this fields:
terr.LDS_DESCRIZIONE_COMUNE,com.DESCRIZIONE,com.CODICE_ISTAT,ind_for.x_cod_istat,ind_for.row_id,cforn.PR_ADDR_ID,cforn.row_id,A.serv_acct_id,a.owner_accnt_id,CLI.IDC_CLIENTE_CRM_KEY, a.status_cd.
any tips for me pls?
i can use PARALLEL? how?
THANKS
A sub select in the Select-Clause can hamper your performance badly. Just try to get rid of it.
You could do something like that
SELECT DISTINCT
--a.row_id FK_SERVIZIO,
--CLI_UNICO.FK_CLIENTE FK_CLIENTE,
CLI.CDC_FISCALE CDC_FISCALE,
--com.descrizione
--CASE WHEN conc.COMUNE IS NOT NULL THEN 1 ELSE 0 END FL_OFFERTABILITA_GAS
decode(test.cnt, 0 'NO', 'SI') FLC_COMUNE_TERR
FROM STG.T_STG_NBA_DT_S_ASSET_G A,
STG.T_STG_PSP_DT_LISTA_COMUNI_TERR terr,
STG.T_STG_NBA_DT_R2DG_COMUNI_G com,
STG.T_STG_NBA_DT_S_ADDR_PER_G ind_for,
--STG.V_DML_NBA_SITO q,
ODS.T_ODS_CRM_DT_CLIENTI_CRM CLI,--ODS.V_ODS_NBA_DT_ASS_CLI_CLIUNICO CLI_UNICO,
STG.T_STG_NBA_DT_S_ORG_EXT_G cforn,
--STG.T_STG_NBA_DT_R2DG_CONCESS_G conc,
(select count(*) cnt from STG.T_STG_NBA_DT_S_ASSET_G a where a.owner_accnt_id=CLI.IDC_CLIENTE_CRM_KEY and status_cd in ('ATTIVATO')) test
WHERE
--CLI.IDC_CLIENTE_CRM_KEY=A.OWNER_ACCNT_ID
terr.LDS_DESCRIZIONE_COMUNE=com.DESCRIZIONE
AND com.CODICE_ISTAT=ind_for.x_cod_istat
AND ind_for.row_id = cforn.PR_ADDR_ID
and cforn.row_id=A.serv_acct_id
I have reviewed the other replies to this problem, but cannot find the appropriate response to my situation. I am trying to divide "actual hours" by "estimated hours". However, estimated hours can be null (no entry) or zero. Actual hours can be zero. So when I get to the division statement, I can't have estimated hours as null or actual hours as zero. My "coalesce" statements don't appear to be helping. Any advice would be helpful.
SELECT PUV.ProjectName, PUV.[Project ID], PUV.[Project Director], PUV.[Project Owner (Manager)], PUV.[Project Type1], **COALESCE( PUV.[Estimated Hours], 0 ) AS EstHours
,PUV.ProjectStatusDate, PUV.ProjectStartDate, PUV.ProjectBaseline0StartDate, PUV.ProjectActualStartDate, PUV.ProjectStartVariance, PUV.ProjectBaseline0FinishDate
,PUV.ProjectFinishDate, PUV.ProjectFinishVariance, PUV.ProjectActualFinishDate, PUV.ProjectWork, PUV.ProjectBaseline0Work, PUV.ProjectActualWork, PUV.ProjectWorkVariance, PUV.ProjectRemainingWork
,PUV.[Project Phase], PUV.[Hold - Canceled Indicator], CWI.StageName, TB.TB_BASE_NUM, MAX (TB.CREATED_DATE) RecentBaseline
,CASE WHEN PUV.[Estimated Hours] is null then 0 END AS [Estimated%]
,Case When PUV.ProjectActualWork <> 0 THEN cast(COALESCE(PUV.ProjectActualWork,0) as DECIMAL(20,2) )/Cast(COALESCE(PUV.[Estimated Hours],0)as decimal(20,2)) Else 0 End AS [Estimated%]*
--DATEDIFF(day, PUV.ProjectBaseline0FinishDate, PUV.ProjectFinishDate)
FROM MSP_EpmProject_UserView AS PUV
LEFT OUTER JOIN (
SELECT WSI.ProjectUID, WP.PhaseName, WP.PhaseUID, WS.StageName, WS.StageUID
FROM MSP_EpmWorkflowStage AS WS
INNER JOIN MSP_EpmWorkflowPhase AS WP ON WS.PhaseUID = WP.PhaseUID
INNER JOIN MSP_EpmWorkflowStatusInformation AS WSI ON WS.StageUID = WSI.StageUID AND WSI.StageEntryDate IS NOT NULL AND (WSI.StageStatus != 0 AND WSI.StageStatus != 4)
) AS CWI ON PUV.ProjectUID = CWI.ProjectUID
JOIN sps_ppm_IT_Published.dbo.MSP_TASK_BASELINES AS TB ON PUV.ProjectUID = TB.PROJ_UID
WHERE TB.TB_BASE_NUM = 0
GROUP BY PUV.ProjectName, PUV.[Project ID], PUV.[Project Director], PUV.[Project Owner (Manager)], PUV.[Project Type1], PUV.[Estimated Hours]
,PUV.ProjectStatusDate, PUV.ProjectStartDate, PUV.ProjectBaseline0StartDate, PUV.ProjectActualStartDate, PUV.ProjectStartVariance, PUV.ProjectBaseline0FinishDate
,PUV.ProjectFinishDate, PUV.ProjectFinishVariance, PUV.ProjectActualFinishDate, PUV.ProjectWork, PUV.ProjectBaseline0Work, PUV.ProjectActualWork, PUV.ProjectWorkVariance, PUV.ProjectRemainingWork
,PUV.[Project Phase], PUV.[Hold - Canceled Indicator], CWI.StageName, TB.TB_BASE_NUM
ORDER BY PUV.ProjectName
Your title is utterly unrelated to the question and posting a super long, aliased query from your database is not a great way to get help.
Luckily, I was curious enough to see whether "msg-8134-level-16-state-1-line-1" was a secret message from Mars that I checked it out.
Anyway, here's a small example of how to use a CASE statement to avoid division by zero:
SELECT
CASE WHEN example.estimated_hours != 0 AND example.estimated_hours IS NOT NULL
THEN 100 / example.estimated_hours
ELSE 0 END AS ratio
FROM (
SELECT estimated_hours
FROM (
VALUES (0), (1), (NULL), (2), (3))
AS mock_data (estimated_hours))
AS example;
You can just copy/paste that into your SQL terminal and run it to see the output:
ratio
-------
0
100
0
50
33
(5 rows)