create table fails in loop (SQL Server) - sql

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.

Related

Brent Ozar's SQL Check Scripts - Memory/CPU/IO Concerns?

How careful do I need to be using Brent Ozar's free SQL health check scripts on a SQL Server 2016 production machine that's very full and very busy already? Has anyone run into memory, CPU or I/O issues running any of the following? Thanks for any feedback.
sp_Blitz
sp_BlitzCache
sp_BlitzFirst
sp_BlitzIndex
sp_BlitzLock
sp_BlitzQueryStore
sp_BlitzWho
sp_WhoIsActive (Adam Machanic)
I would not be without it. We have Redgate and I use Brents tools more often.
Our database is 3 Tb and has approx. 1500 queries per second and have never experienced any problems.
Made a custom sp_BlitzWho_Ext which relys on the sp_BlitzWho.
It takes the result of sp_BlitzWho. Puts it in a temp table so I can add a filter. Also cursors are identified and converted so you can see the actual query.
The SQL for dropping the plan_cache of each of them are there - so whenever we get a dumb plan its easy to find and drop the right one.
It now only takes 5 seconds to identify the culprit and get the plan dropped.
First I created a Function to get the query text from the Cursor
create function [dbo].[CursorQuery]
(
#session_id int
) returns nvarchar(255)
as
begin
declare #ret nvarchar(255) = null
SELECT #ret = t.text
FROM sys.dm_exec_cursors (#session_id) c
LEFT JOIN sys.dm_exec_sessions AS es ON c.session_id = es.session_id
CROSS APPLY sys.dm_exec_sql_text (c.sql_handle) t
return #ret
end
Then the stored procedure
CREATE PROCEDURE [dbo].[sp_BlitzWho_Ext]
AS
BEGIN
CREATE TABLE #BlitzWhoResult
(
[run_date] VARCHAR(255),
[elapsed_time] [varchar](41) NULL,
[session_id] [smallint] NOT NULL,
[database_name] [nvarchar](128) NULL,
[query_text] [nvarchar](max) NULL,
[query_plan] [xml] NULL,
[live_query_plan] [xml] NULL,
[query_cost] [float] NULL,
[status] [nvarchar](30) NOT NULL,
[wait_info] [nvarchar](max) NULL,
[top_session_waits] [nvarchar](max) NULL,
[blocking_session_id] [smallint] NULL,
[open_transaction_count] [int] NULL,
[is_implicit_transaction] [int] NOT NULL,
[nt_domain] [nvarchar](128) NULL,
[host_name] [nvarchar](128) NULL,
[login_name] [nvarchar](128) NOT NULL,
[nt_user_name] [nvarchar](128) NULL,
[program_name] [nvarchar](128) NULL,
[fix_parameter_sniffing] [nvarchar](150) NULL,
[client_interface_name] [nvarchar](32) NULL,
[login_time] [datetime] NOT NULL,
[start_time] [datetime] NULL,
[request_time] [datetime] NULL,
[request_cpu_time] [int] NULL,
[request_logical_reads] [bigint] NULL,
[request_writes] [bigint] NULL,
[request_physical_reads] [bigint] NULL,
[session_cpu] [int] NOT NULL,
[session_logical_reads] [bigint] NOT NULL,
[session_physical_reads] [bigint] NOT NULL,
[session_writes] [bigint] NOT NULL,
[tempdb_allocations_mb] [decimal](38, 2) NULL,
[memory_usage] [int] NOT NULL,
[estimated_completion_time] [bigint] NULL,
[percent_complete] [real] NULL,
[deadlock_priority] [int] NULL,
[transaction_isolation_level] [varchar](33) NOT NULL,
[degree_of_parallelism] [smallint] NULL,
[last_dop] [bigint] NULL,
[min_dop] [bigint] NULL,
[max_dop] [bigint] NULL,
[last_grant_kb] [bigint] NULL,
[min_grant_kb] [bigint] NULL,
[max_grant_kb] [bigint] NULL,
[last_used_grant_kb] [bigint] NULL,
[min_used_grant_kb] [bigint] NULL,
[max_used_grant_kb] [bigint] NULL,
[last_ideal_grant_kb] [bigint] NULL,
[min_ideal_grant_kb] [bigint] NULL,
[max_ideal_grant_kb] [bigint] NULL,
[last_reserved_threads] [bigint] NULL,
[min_reserved_threads] [bigint] NULL,
[max_reserved_threads] [bigint] NULL,
[last_used_threads] [bigint] NULL,
[min_used_threads] [bigint] NULL,
[max_used_threads] [bigint] NULL,
[grant_time] [varchar](20) NULL,
[requested_memory_kb] [bigint] NULL,
[grant_memory_kb] [bigint] NULL,
[is_request_granted] [varchar](39) NOT NULL,
[required_memory_kb] [bigint] NULL,
[query_memory_grant_used_memory_kb] [bigint] NULL,
[ideal_memory_kb] [bigint] NULL,
[is_small] [bit] NULL,
[timeout_sec] [int] NULL,
[resource_semaphore_id] [smallint] NULL,
[wait_order] [varchar](20) NULL,
[wait_time_ms] [varchar](20) NULL,
[next_candidate_for_memory_grant] [varchar](3) NOT NULL,
[target_memory_kb] [bigint] NULL,
[max_target_memory_kb] [varchar](30) NULL,
[total_memory_kb] [bigint] NULL,
[available_memory_kb] [bigint] NULL,
[granted_memory_kb] [bigint] NULL,
[query_resource_semaphore_used_memory_kb] [bigint] NULL,
[grantee_count] [int] NULL,
[waiter_count] [int] NULL,
[timeout_error_count] [bigint] NULL,
[forced_grant_count] [varchar](30) NULL,
[workload_group_name] [sysname] NULL,
[resource_pool_name] [sysname] NULL,
[context_info] [varchar](128) NULL,
[query_hash] [binary](8) NULL,
[query_plan_hash] [binary](8) NULL,
[sql_handle] [varbinary] (64) NULL,
[plan_handle] [varbinary] (64) NULL,
[statement_start_offset] INT NULL,
[statement_end_offset] INT NULL
)
INSERT INTO #BlitzWhoResult
EXEC [dbo].[sp_BlitzWho] #ShowSleepingSPIDs = 1, #ExpertMode = 1, #MinElapsedSeconds = 1
SELECT [program_name],
[session_id],
CASE WHEN [query_text] LIKE 'FETCH API_CURSOR%'
THEN CursorQuery(session_id)
ELSE query_text
END AS [query_text],
[query_plan],
[fix_parameter_sniffing] AS [drop_cached_plan_sql],
[status],
[wait_info],
[login_name]
from #BlitzWhoResult
where database_name = 'PUT_YOUR_DATABASENAME_HERE' -- and... add more filters?
DROP TABLE #BlitzWhoResult
END
So.. I really enjoy Brents tool as well as his videos and sense of humour

SQL AZURE : An error occurred while executing GlobalQuery operation: Large object column support is limited to only nvarchar(max) data type

Sql azure query: after creating external table i run select query to get data from external table but this error occures!
i removed all columns with datatype = nvarchar(max) but also the problem have not been solved yet!
Code to create external table:
CREATE External TABLE [dbo].[tbl_threads_controlPanel_v](
[thread_id] [varchar](6) NOT NULL,
[thread_desc_criteria] [varchar](300) NOT NULL,
[thread_desc_formula] [varchar](300) NOT NULL,
[thread_type] [char](1) NOT NULL,
[detectType] [char](1) NOT NULL,
[detailed_qry] [nvarchar](300) NULL,
[bottomup_qry] [nvarchar](300) NULL,
[period_desc] [char](1) NULL,
[period_value] [int] NULL,
[period_value_range] [varchar](50) NULL,
--[cond_attribute] [nvarchar](max) NULL,
[cond_min_max_limit] [varchar](30) NULL,
[cond_desc] [varchar](60) NULL,
[active] [char](1) NULL,
[mature] [char](1) NULL,
[pkg_run] [char](1) NULL,
[thread_index] [int] NULL,
[thread_weight] [numeric](12, 11) NULL,
[thread_noti_type] [char](1) NULL,
[notif_id] [varchar](9) NULL,
[amt_type] [nchar](5) NULL--,
--[report_Columns] [nvarchar](max) NULL,
--[OS_Columns] [nvarchar](max) NULL
)
with(DATA_SOURCE = MyElasticDBQueryDataSrc3)
And this is the select query:
select * from dbo.[tbl_threads_controlPanel_v]
Please help ..
Thanks in advance.
UPDATE 2:
This is original tbl_threads definition
USE [DB_IFDPS_ControlPanel]
GO
/****** Object: Table [dbo].[tbl_threads] Script Date: 10/26/2016 8:51:09 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[tbl_threads](
[thread_id] [varchar](6) NOT NULL,
[thread_desc_criteria] [varchar](300) NOT NULL,
[thread_desc_formula] [varchar](300) NOT NULL,
[thread_type] [char](1) NOT NULL,
[detectType] [char](1) NOT NULL,
[detailed_qry] [text] NULL,
[bottomup_qry] [text] NULL,
[period_desc] [char](1) NULL,
[period_value] [int] NULL,
[period_value_range] [varchar](50) NULL,
[cond_attribute] [nvarchar](max) NULL,
[cond_min_max_limit] [varchar](30) NULL,
[cond_desc] [varchar](60) NULL,
[active] [char](1) NULL,
[mature] [char](1) NULL,
[pkg_run] [char](1) NULL,
[thread_index] [int] NULL,
[thread_weight] [numeric](12, 11) NULL,
[thread_noti_type] [char](1) NULL,
[notif_id] [varchar](9) NULL,
[amt_type] [nchar](5) NULL,
[report_Columns] [nvarchar](max) NULL,
[OS_Columns] [nvarchar](max) NULL,
CONSTRAINT [PK_tbl_threads] PRIMARY KEY CLUSTERED
(
[thread_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
It looks like this is not the whole story.
The problem seems to be not with the varchar(max) columns but with a column that is defined somewhere else as a LOB but in the external table is defined otherwise than varchar(max)
Thanks for adding the relevant DDL.
The issue is most likely with the text columns
CREATE External TABLE [dbo].[tbl_threads_controlPanel_v](
...
[detailed_qry] [nvarchar](300) NULL,
[bottomup_qry] [nvarchar](300) NULL,
...
CREATE TABLE [dbo].[tbl_threads]
...
[detailed_qry] [text] NULL,
[bottomup_qry] [text] NULL,
...
P.s.
https://msdn.microsoft.com/en-us/library/ms187993.aspx
IMPORTANT! ntext, text, and image data types will be removed in a future version of SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.

how to prefix identity column character in msSQL

How can I alter a table's primary identity column to include a letter before the number? I have a table named vendor_master with a primary key VendorID that I would like to store as v1,v2,v3 and so on
CREATE TABLE [dbo].[vendor_master](
[vendorID] [int] IDENTITY(1,1) NOT NULL,
[Vname] [nvarchar](50) NOT NULL,
[Email] [nvarchar](50) NOT NULL,
[Mobile] [bigint] NULL,
[Landline] [bigint] NULL,
[Address] [nvarchar](max) NOT NULL,
[Pincode] [int] NOT NULL)
If it's important to you to have the field in your table, try the following:
CREATE TABLE [dbo].[vendor_master]
(
[vendorID] [int] IDENTITY(1,1) NOT NULL,
[Vname] [nvarchar](50) NOT NULL,
[Email] [nvarchar](50) NOT NULL,
[Mobile] [bigint] NULL,
[Landline] [bigint] NULL,
[Address] [nvarchar](max) NOT NULL,
[Pincode] [int] NOT NULL,
[VendorKey] AS ('v' +CONVERT([varchar](10),[vendorID])) PERSISTED
)
Of course, that will yield you some weird results when sorting, so you might consider padding the data with zeroes to make it a consistent length:
CREATE TABLE [dbo].[vendor_master]
(
[vendorID] [int] IDENTITY(1,1) NOT NULL,
[Vname] [nvarchar](50) NOT NULL,
[Email] [nvarchar](50) NOT NULL,
[Mobile] [bigint] NULL,
[Landline] [bigint] NULL,
[Address] [nvarchar](max) NOT NULL,
[Pincode] [int] NOT NULL,
[VendorKey] AS ('v' +RIGHT('000000000' + CONVERT([varchar](10),[vendorID]),10)) PERSISTED
)
You can't actually do what you are asking. Anyway, there is no reason to add the same letter to the front of a fields value. Instead add the letter in your SELECT statment:
SELECT CONCAT('v', vendorID) AS VendorIDWithPrefix, Vname, Email, Mobile
FROM vendor_master

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,