How do I rewrite this to avoid a cursor - sql

I have this function written in T-SQL on SQL Server 2005. I am not as against cursors as some are but I always see people saying 99% of all cursors can be re-written to avoid their use.
I have this function:
CREATE FUNCTION WhereUsed(#ItemID varchar(100))
RETURNS varchar(MAX)
AS
BEGIN
DECLARE #Items CURSOR
DECLARE #ParentItem varchar(100)
DECLARE #WhereUsed varchar(MAX)
SET #WhereUsed = ''
SET #Items = CURSOR FAST_FORWARD
FOR
SELECT PST_ParentItemID FROM PST WHERE PST_CompItemID = #ItemID
OPEN #Items
FETCH NEXT FROM #Items
INTO #ParentItem
WHILE ##FETCH_STATUS = 0
BEGIN
SET #WhereUsed = #WhereUsed + #ParentItem + ', '
FETCH NEXT FROM #Items
INTO #ParentItem
END
IF LEN(#WhereUsed) > 2
SET #WhereUsed = LEFT(#WhereUsed, LEN(#WhereUsed) - 2)
RETURN #WhereUsed
END
Which will get all the items where a part is used, PST is ParentStructureTable. Think BOM (Bill Of Materials)
It will be used like this:
SELECT Field1, Field2, dbo.WhereUsed(ItemID), Field3 FROM Item
And return something like this:
S6110-23350-41, 61070-10161-012, R6112-23027-41
How could this be done without using a cursor?
EDIT:
Sample data
SELECT PST_ParentItemID FROM PST WHERE PST_CompItemID = #ItemID
Can return
PST_ParentItemID
----------------
S6110-23350-41
61070-10161-012
R6112-23027-41
Its really a simple select statement, not sure how the DDL will help but here it is:
CREATE TABLE [dbo].[ProductStructure](
[PST_RecordID] [uniqueidentifier] NOT NULL,
[PST_PSH_RecordID] [uniqueidentifier] NOT NULL,
[PST_IMA_RecordID] [uniqueidentifier] NOT NULL,
[PST_EffStartDate] [datetime] NOT NULL,
[PST_EffStopDate] [datetime] NULL,
[PST_DisplayOrder] [int] NOT NULL CONSTRAINT [DF__ProdStruc__PST_DisplayOrder] DEFAULT ((0)),
[PST_Available] [bit] NOT NULL CONSTRAINT [DF__ProdStruc__PST_Available] DEFAULT ((1)),
[PST_AddDate] [datetime] NOT NULL CONSTRAINT [DF__ProdStruc__PST_AddDate__192BAC54] DEFAULT (getdate()),
[PST_QtyPerAssy] [float] NOT NULL CONSTRAINT [DF__ProdStruc__PST_QtyPerA__1A1FD08D] DEFAULT ((1)),
[PST_ScrapQty] [float] NOT NULL CONSTRAINT [DF__ProdStruc__PST_ScrapQt__1B13F4C6] DEFAULT ((0)),
[PST_PlanType] [nvarchar](11) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL CONSTRAINT [DF__ProdStruc__PST_PlanTyp__1C0818FF] DEFAULT ('MRP'),
[PST_ScrapPercent] [float] NOT NULL CONSTRAINT [DF__ProdStruc__PST_ScrapPe__1CFC3D38] DEFAULT ((0)),
[PST_LeadTimeOffsetDays] [smallint] NOT NULL CONSTRAINT [DF__ProdStruc__PST_LeadTim__1DF06171] DEFAULT ((0)),
[PST_RoutSeqID] [nvarchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[PST_EngChangeOrderID] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[PST_FindID] [nvarchar](5) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[PST_Comments] [ntext] COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[PST_UseAbsQtyFlag] [bit] NOT NULL CONSTRAINT [DF__ProdStruc__PST_UseAbsQ__1EE485AA] DEFAULT ((0)),
[PST_IgnoreCostFlag] [bit] NOT NULL CONSTRAINT [DF__ProdStruc__PST_IgnoreC__1FD8A9E3] DEFAULT ((0)),
[PST_PlanningPercent] [float] NOT NULL CONSTRAINT [DF__ProdStruc__PST_Plannin__20CCCE1C] DEFAULT ((0)),
[PST_EMP_RecordID] [uniqueidentifier] NULL,
[PST_LastModifiedDate] [datetime] NULL,
[PST_PurchPOWO] [bit] NOT NULL CONSTRAINT [DF__ProdStruc__PST_PurchPO__21C0F255] DEFAULT ((0)),
[PST_AgileCreatedDate] [datetime] NULL,
[PST_ArchiveDate] [datetime] NULL,
[PST_UserDef1] [nvarchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[PST_UserDef2] [nvarchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[PST_UserDef3] [nvarchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[PST_UserDef4] [nvarchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[PST_UserDef5] [nvarchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[timestamp] [timestamp] NULL,
[PST_SWImportFlag] [bit] NOT NULL CONSTRAINT [DF_ProductStructure_PST_SWImportFlag] DEFAULT ((0)),
[PST_CopiedFromRecordID] [uniqueidentifier] NULL,
[PST_OnPicklist] [bit] NOT NULL DEFAULT ((1)),
[PST_CID_DocumentID] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
CONSTRAINT [PK_ProductStructure] PRIMARY KEY NONCLUSTERED
(
[PST_RecordID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

It appears you are simply returning a concatenated string. Try this
DECLARE #WhereUsed varchar(MAX)
SET #WhereUsed = ''
SELECT #whereUsed=#whereUsed+PST_ParentItemID+', 'FROM PST
WHERE PST_CompItemID = #ItemID
IF LEN(#WhereUsed) > 2
SET #WhereUsed = LEFT(#WhereUsed, LEN(#WhereUsed) - 2)

Related

Query not using index in exists statement

I have the index IDX_tbl_SpeedRun_StatusTypeID_GameID_CategoryID_LevelID_PlusInclude on table dbo.tbl_SpeedRun below. The exists statement in the query below is taking a while (1m 10s) saying there is a missing index ON [dbo].[tbl_SpeedRun] ([StatusTypeID],[LevelID]).
Why is the exists statement not using the index I created? It already includes the columns [StatusTypeID],[LevelID].
Table:
CREATE TABLE [dbo].[tbl_SpeedRun]
(
[OrderValue] [int] NOT NULL IDENTITY(1,1),
[ID] [varchar] (50) NOT NULL,
[StatusTypeID] [int] NOT NULL,
[GameID] [varchar] (50) NOT NULL,
[CategoryID] [varchar] (50) NOT NULL,
[LevelID] [varchar] (50) NULL,
[SubCategoryVariableValues] [varchar] (1000) NULL,
[PlayerIDs] [varchar] (1000) NULL,
[PlatformID] [varchar] (50) NULL,
[RegionID] [varchar] (50) NULL,
[IsEmulated] [bit] NOT NULL,
[Rank] [int] NULL,
[PrimaryTime] [bigint] NULL,
[RealTime] [bigint] NULL,
[RealTimeWithoutLoads] [bigint] NULL,
[GameTime] [bigint] NULL,
[Comment] [varchar] (MAX) NULL,
[ExaminerUserID] [varchar] (50) NULL,
[RejectReason] [varchar] (MAX) NULL,
[SpeedRunComUrl] [varchar] (2000) NOT NULL,
[SplitsUrl] [varchar] (2000) NULL,
[RunDate] [datetime] NULL,
[DateSubmitted] [datetime] NULL,
[VerifyDate] [datetime] NULL,
[ImportedDate] [datetime] NOT NULL CONSTRAINT [DF_tbl_SpeedRun_ImportedDate] DEFAULT(GETDATE()),
[ModifiedDate] [datetime] NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[tbl_SpeedRun]
ADD CONSTRAINT [PK_tbl_SpeedRun]
PRIMARY KEY NONCLUSTERED ([ID]) WITH (FILLFACTOR=90) ON [PRIMARY]
GO
CREATE CLUSTERED INDEX [IDX_tbl_SpeedRun_OrderValue]
ON [dbo].[tbl_SpeedRun] ([OrderValue]) WITH (FILLFACTOR=90) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IDX_tbl_SpeedRun_StatusTypeID_GameID_CategoryID_LevelID_PlusInclude]
ON [dbo].[tbl_SpeedRun] ([StatusTypeID], [GameID], [CategoryID],[LevelID])
INCLUDE ([SubCategoryVariableValues], [PlayerIDs], [Rank],[PrimaryTime])
GO
Query:
SELECT
CASE
WHEN EXISTS (SELECT 1 FROM dbo.tbl_SpeedRun rn WITH (NOLOCK)
WHERE rn.LevelID = l.ID AND rn.StatusTypeID = 1)
THEN 1
ELSE 0
END
FROM
dbo.tbl_Level l WITH (NOLOCK)
WHERE
l.GameID = 'pd0wq901'
ORDER BY
l.OrderValue
This is the from clause of your subquery:
WHERE rn.LevelID = l.ID AND rn.StatusTypeID = 1
A helpful index for this predicate would involve the two columns, in any order.
Your existing index does not satisfy that requirement. It has columns:
[StatusTypeID], [GameID], [CategoryID], [LevelID])
INCLUDE ([SubCategoryVariableValues], [PlayerIDs], [Rank], [PrimaryTime])
Both columns are here, but buried within others - so the database cannot take advantage of it to speed up the subquery.
Bottom line: creating a large index that involves a lot of columns does not speed up queries by default. Instead, you can analyze each query individually and define the proper optimization.

How to implement procedure to create document with header and lines in 2 different tables SQL

I'm working on an android application for inventory. It has an Sql Server Database. I have to tables like:
InventoryHeader
[id] [int] IDENTITY(1,1) NOT NULL,
[transactionumber] [varchar](30) NOT NULL,
[storeroom] [varchar](15) NULL,
[transactiontype] [varchar](15) NOT NULL,
[projectname] [varchar](50) NULL,
[projectid] [int] NULL,
[comments] [varchar](250) NULL,
[addedBy] [varchar](20) NOT NULL,
[date] [datetime] NOT NULL
Inventorylines
[id] [int] IDENTITY(1,1) NOT NULL,
[transactionumber] [varchar](30) NOT NULL,
[linenumber] [int] NOT NULL,
[storeroom] [varchar](15) NULL,
[locationtype] [varchar](10) NULL,
[storeroomlocationid] [int] NULL,
[itemnum] [varchar](20) NULL,
[quantity] [decimal](10, 3) NULL,
[uom] [varchar](10) NULL,
[unitprice] [decimal](10, 3) NULL,
[lineprice] [decimal](10, 3) NULL
Which is the best way to make an api to create a document with header and one or more lines? I managed to create a procedure to create the header of the document but not the lines. Any suggestions?
Here is the procedure I have:
`CREATE PROCEDURE [dbo].[spAddNewInventoryTr]
#Transactionumber varchar(30) ,
#Storeroom varchar(15) ,
#Transactiontype VArchar(15) ,
#Projectname VArchar(50) ,
#Comments varchar(250) ,
#Addedby varchar(20) ,
#Date datetime
AS
BEGIN
DECLARE #Projectid int
exec #Projectid = projectidproc #Projectname, #Projectid output
INSERT INTO inventoryheader(transactionumber,storeroom, transactiontype,
projectname, projectid, comments, addedBy,date)
VALUES(#Transactionumber,#Storeroom,
#Transactiontype,#Projectname,#Projectid , #Comments,#Addedby ,#Date)
END
GO`

create table fails in loop (SQL Server)

I have a sql script that creates tables for each db in my sql server. However it fails on one create table script. Eg the
CREATE TABLE [dbo].[Mx_Poll_Tags]
command. What is wrong with this? I don't see it.
The weird part is when I one by one run the scripts in a query window they all work fine. Only is this particular proc it fails.
The error states:
Msg 173, Level 15, State 1, Line 71
The definition for column 'Unit' must include a data type.
The create script is made by SQL Server itself by scripting an existing Mx_Poll_Tags table as CreateTo.
Does anyone see what the error is?
BEGIN
declare #proc nvarchar(max)
set #proc='if ''?'' like ''Client_%''
begin
use [?]
print ''?''
DROP TABLE [dbo].[ManualMetersInput]
DROP TABLE [dbo].[ManualMeterActions]
DROP TABLE [dbo].[ManualMeters]
DROP TABLE [dbo].[MX_Poll]
--DROP TABLE [dbo].[Mx_Poll_Tags]
DROP TABLE [dbo].[MX_Poll_Info]
DROP TABLE [dbo].[MX_Poll_Logs]
DROP TABLE [dbo].[MX_Poll_QA]
--DROP TABLE [dbo].[MX_Poll_Vars]
CREATE TABLE [dbo].[ManualMeters]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Ean] [varchar](max) NULL,
[Period] [int] NULL,
[TagTable] [varchar](max) NULL,
[TagTableId] [varchar](max) NOT NULL,
[Overflow] [int] NULL,
[TZ] [varchar](max) NULL,
) ON [PRIMARY]
CREATE TABLE [dbo].[ManualMetersInput]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Timestamp] [datetime2](7) NOT NULL,
[ManualMeterId] [int] NOT NULL,
[Value] [decimal](18, 3) NOT NULL,
[IsOverflow] [bit] NOT NULL,
[ImportDate] [datetime2](7) NOT NULL,
) ON [PRIMARY]
CREATE TABLE [dbo].[ManualMeterActions]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[ManualMeterId] [int] NOT NULL,
[UserId] [int] NOT NULL,
[Type] [nvarchar](max) NOT NULL,
) ON [PRIMARY]
CREATE TABLE [dbo].[MX_Poll]
(
[timestamp] [datetime2](7) NOT NULL,
[localtimestamp] [datetime2](7) NOT NULL,
) ON [PRIMARY]
CREATE TABLE [dbo].[MX_Poll_Info]
(
[timestamp] [datetime2](7) NOT NULL,
[info] [nvarchar](max) NOT NULL,
) ON [PRIMARY]
CREATE TABLE [dbo].[MX_Poll_Logs]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[timestamp] [datetime2](7) NOT NULL,
[Message] [nvarchar](max) NULL,
) ON [PRIMARY]
CREATE TABLE [dbo].[MX_Poll_QA]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[timestamp] [datetime2](7) NOT NULL,
[tag] [nvarchar](max) NULL,
[QA] [int] NULL
) ON [PRIMARY]
-- error here
CREATE TABLE [dbo].[Mx_Poll_Tags]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](800) NOT NULL,
[Unit] [int] NOT NULL,
[FieldName] [nvarchar](100) NULL,
[ScaleFromMin] [decimal](18, 3) NULL,
[ScaleFromMax] [decimal](18, 3) NULL,
[ScaleToMin] [decimal](18, 3) NULL,
[ScaleToMax] [decimal](18, 3) NULL,
[DeltaOfKwhCounter_Id] [int] NULL,
[Visible] [int] NULL,
[Type] [nvarchar](50) NULL,
[Enable] [int] NULL,
[Content] [int] NULL,
[Quantity] [int] NULL,
[Signal] [int] NULL,
[SignalDescription] [nvarchar](max) NULL,
[Connection] [nvarchar](max) NULL,
[Cable] [nvarchar](max) NULL,
[Comments] [nvarchar](max) NULL,
[UsedForPrediction_0] [bit] NOT NULL,
[RelatedToPrediction_0] [bit] NOT NULL,
[CalculatedByPredictionNo] [int] NULL,
) ON [PRIMARY]
end';
--print #proc;
exec sp_MSForEachDB #proc
END
GO
Can you try it with just creating that table?
Also, can you eliminate the "begin" and "end"? Based on this thread: http://www.sqlservercentral.com/Forums/Topic808714-8-1.aspx
I don't have enough reputation to make this a comment.
EDIT:
By default, sys.sp_MSforeachdb #command1 has a parameter length of nvarchar(2000). Even though you're passing in a varchar(max), anything over 2000 is being truncated.

Update on view over partitioned tables updating all clustered indexes

We have a table, which is partitioned through a date field into separate years.
There is a view over all of these tables (Call)
Schema is as follows:
CREATE TABLE [dbo].[Call_2015](
[calID] [uniqueidentifier] NOT NULL,
[calPackageID] [int] NULL,
[calClientID] [int] NULL,
[calStartDate] [datetime] NOT NULL,
[calEndDate] [datetime] NOT NULL,
[calTimeIn] [char](5) NULL,
[calTimeOut] [char](5) NULL,
[calMinutes] [smallint] NULL,
[calPreferredTimeIn] [char](5) NULL,
[calPreferredTimeOut] [char](5) NULL,
[calActualTimeIn] [char](5) NULL,
[calActualTimeOut] [char](5) NULL,
[calActualMinutes] [smallint] NULL,
[calConfirmed] [smallint] NULL,
[calCarerID] [int] NULL,
[calRepCarerID] [int] NULL,
[calOriginalCarerID] [int] NULL,
[calContractID] [int] NULL,
[calNeedID] [int] NULL,
[calMedicationID] [int] NULL,
[calFrequency] [smallint] NULL,
[calFromDate] [datetime] NULL,
[calWeekNo] [smallint] NULL,
[calAlert] [smallint] NULL,
[calNoLeave] [smallint] NULL,
[calTimeCritical] [smallint] NULL,
[calStatus] [smallint] NULL,
[calClientAwayReasonID] [int] NULL,
[calCarerAwayReasonID] [int] NULL,
[calOutsideShift] [smallint] NULL,
[calHistoryID] [int] NULL,
[calInvoiceID] [int] NULL,
[calWagesheetID] [int] NULL,
[calReasonID] [int] NULL,
[calCallConfirmID] [varchar](50) NULL,
[calCreated] [datetime] NULL,
[calUpdated] [datetime] NULL,
[calVariation] [int] NULL,
[calVariationUserID] [int] NULL,
[calException] [smallint] NULL,
[calRetained] [smallint] NULL,
[calDoubleUpID] [uniqueidentifier] NULL,
[calDoubleUpOrder] [smallint] NULL,
[calNeedCount] [smallint] NULL,
[calNoStay] [smallint] NULL,
[calCoverCarerID] [int] NULL,
[calPayAdjustment] [real] NULL,
[calChargeAdjustment] [real] NULL,
[calTeamID] [int] NULL,
[calExpenses] [money] NULL,
[calMileage] [real] NULL,
[calOverrideStatus] [smallint] NULL,
[calLocked] [smallint] NULL,
[calDriver] [smallint] NULL,
[calPostcode] [char](10) NULL,
[calDayCentreID] [int] NULL,
[calMustHaveCarer] [smallint] NULL,
[calRoleID] [int] NULL,
[calUnavailableCarerID] [int] NULL,
[calClientInformed] [smallint] NULL,
[calFamilyInformed] [smallint] NULL,
[calMonthlyDay] [smallint] NULL,
[calOriginalTimeIn] [char](5) NULL,
[calLeadCarer] [smallint] NULL,
[calCallTypeID] [int] NULL,
[calActualStartDate] [datetime] NULL,
[calActualEndDate] [datetime] NULL,
[Table_Year] [int] NOT NULL,
CONSTRAINT [PK_Call_2015] PRIMARY KEY CLUSTERED
(
[Table_Year] ASC,
[calID] ASC,
[calStartDate] ASC,
[calEndDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[Call_2015] WITH CHECK ADD CONSTRAINT [CK_Call_Year_2015] CHECK (([Table_Year]=(2015)))
GO
ALTER TABLE [dbo].[Call_2015] CHECK CONSTRAINT [CK_Call_Year_2015]
GO
ALTER TABLE [dbo].[Call_2015] WITH CHECK ADD CONSTRAINT [CK_calStartDate_2015] CHECK (([calStartDate]>=CONVERT([datetime],'01 Jan 2015 00:00:00',(0)) AND [calStartDate]<=CONVERT([datetime],'31 DEC 2015 23:59:59',(0))))
GO
ALTER TABLE [dbo].[Call_2015] CHECK CONSTRAINT [CK_calStartDate_2015]
GO
ALTER TABLE [dbo].[Call_2015] ADD CONSTRAINT [DF_Call_2015_Table_Year] DEFAULT ((2015)) FOR [Table_Year]
GO
The update to the table is as follows:
UPDATE Call SET
calStartDate = CASE
WHEN calFrequency = 14 THEN dbo.funDate(#MonthlyDay, MONTH(calStartDate), YEAR(calStartDate))
WHEN calFrequency IN (15,16) THEN dbo.funMonthlyCallDate(calFrequency, #MonthlyDay, calStartDate)
ELSE DateAdd(d, #StartDay-1, (calStartDate - datepart(dw,calStartDate)+1))
END,
calEndDate = CASE
WHEN calFrequency = 14 THEN dbo.funDate(#MonthlyDay + #EndDay - #StartDay, MONTH(calStartDate), YEAR(calStartDate))
WHEN calFrequency IN (15,16) THEN DATEADD(D, #EndDay - #StartDay, dbo.funMonthlyCallDate(calFrequency, #MonthlyDay, calStartDate))
ELSE DateAdd(d, #StartDay-1+#DayCount, (calStartDate - datepart(dw,calStartDate)+1))
END,
calTimeIn = #TimeIn,
calTimeOut = #TimeOut,
calMinutes = #Minutes,
calMonthlyDay = #MonthlyDay,
calClientInformed = Null,
calFamilyInformed = Null
WHERE calPackageID = #PackageID
AND calClientID = #ClientID
AND calWeekNo = #WeekNo
AND (DatePart(dw, calStartDate) = #OriginalDay OR calFrequency IN (14,15,16))
AND calStartDate BETWEEN #StartDate AND #EndDate
AND (calInvoiceID = 0 OR calInvoiceID Is Null OR #InvoicesFinalised = 1)
AND (calWagesheetID = 0 OR calWagesheetID Is Null OR #WagesFinalised = 1)
AND (calLocked = 0 OR calLocked Is Null)
AND (Table_Year = YEAR(#StartDate)
OR Table_Year =YEAR(#EndDate))
The SP updates a batch of rows dependant of input into #StartDate and #EndDate (updates all rows with a calStartDate between the two)
The problem then comes with the execution plan. There are huge IO costs to the operation, and I've nailed it down to how SQL is dealing with the update.
Currently we have 20 of these tables; partitioned per year. Each update is causing an update of every single table's indexes, regardless of whether the table is actually touched by the update operation or not.
Execution Plan
Below this section it goes on to update, in the exact same manner, every table in the view.
I cannot see why this is, as I have specified the Table_Year (which the table is partitioned on) within the query text. Shouldn't SQL only update the necessary table?

SQL server sys.dm_db_index_physical_stats Remote scan in query plan

I have a query in db A which shows the index fragmentation level and recent rebuilt or re-organised status, it cross apply a function B in db C, A and C are on the same instance.
Function B is:
ALTER function [dbo].[B]
(
#db_id int
,#object_id int
,#index_id int
,#partition_number int
,#mode varchar (20)
)
returns #results TABLE (
[database_id] [smallint] NULL,
[object_id] [int] NULL,
[index_id] [int] NULL,
[partition_number] [int] NULL,
[index_type_desc] [nvarchar](60) NULL,
[alloc_unit_type_desc] [nvarchar](60) NULL,
[index_depth] [tinyint] NULL,
[index_level] [tinyint] NULL,
[avg_fragmentation_in_percent] [float] NULL,
[fragment_count] [bigint] NULL,
[avg_fragment_size_in_pages] [float] NULL,
[page_count] [bigint] NULL,
[avg_page_space_used_in_percent] [float] NULL,
[record_count] [bigint] NULL,
[ghost_record_count] [bigint] NULL,
[version_ghost_record_count] [bigint] NULL,
[min_record_size_in_bytes] [int] NULL,
[max_record_size_in_bytes] [int] NULL,
[avg_record_size_in_bytes] [float] NULL,
[forwarded_record_count] [bigint] NULL,
[compressed_page_count] [bigint] NULL
)
begin
insert into #results
select *
from sys.dm_db_index_physical_stats (#db_id, #object_id, #index_id ,#partition_number
,#mode )
return
end
This query takes a long time to execute. I read the query plan, the plan contains a "Remote Scan". I don't understand why is that.
Can anyone help?
Thanks,