Update on view over partitioned tables updating all clustered indexes - sql

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?

Related

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.

In Trigger getting error as error converting data type varchar to numeric

I have a trigger which was working earlier perfectly. But later on, as required I added some more lines into that which is below
declare #imkey numeric(10,0);declare #xmkey numeric(10,0); declare #xsrno numeric(10,0)
select #xmkey=max([Mkey])+1, #xsrno=max([Entry_Sr_No])+1
from erp190516.[dbo].[Inward_Doc_Tracking_Trl] where Ref_Mkey=#imkey;
select #imkey=i.Inward_ref_key from inserted i
insert into erp190516.[dbo].[Inward_Doc_Tracking_Trl]
SELECT #xmkey,#xsrno,[N_UserMkey],'1' [N_Department], 'F' [CStatus_Flag]
,'Requester' [Remarks],'1' [CUser_ID],getdate() [U_Datetime],
,'N' [NStatus_Flag], 'N' [Delete_Flag]
,'1'[CDept_Id],[Ref_Mkey],[No_Of_Days],[Approved_Amount],[Chq_No],[Chq_dated]
,[Chq_Bank],[Chq_Amount],[Vendor_MKey],[Vendor_Comp_Mkey]
,[Project_Mkey],[Program_mkey],[Payment_MKey],[Due_Date],[Updated_Remarks]
,[Updated_Bill_no],[Updated_Bill_Date],[Updated_Bill_Amt]
,[Party_Name],[Acc_mkey],[TotalDeductions],[Broker_Mkey],[Customer_Mkey]
,[Payable_Amt],[Balance_Amt],[Receipt_No],[Po_No],[Bill_No]
,[Disp_through],[Disp_Through_Name],[Site_Id]
FROM erp190516.[dbo].[Inward_Doc_Tracking_Trl] where Ref_Mkey=#imkey
It eexcuted perfectly, but while inserting the data into the table I got error as
Error converting data type varchar to numeric
Table Definition
CREATE TABLE [dbo].[Inward_Doc_Tracking_Trl](
[Mkey] [numeric](18, 0) NOT NULL,
[Entry_Sr_No] [numeric](4, 0) NOT NULL,
[N_UserMkey] [numeric](10, 0) NULL,
[N_Department] [numeric](10, 0) NULL,
[CStatus_Flag] [numeric](8, 0) NOT NULL,
[Remarks] [varchar](500) NULL,
[CUser_ID] [numeric](10, 0) NOT NULL,
[U_Datetime] [datetime] NOT NULL,
[NStatus_Flag] [numeric](10, 0) NOT NULL,
[Delete_Flag] [char](1) NULL,
[CDept_Id] [numeric](10, 0) NOT NULL,
[Ref_Mkey] [numeric](18, 0) NULL,
[No_Of_Days] [int] NULL,
[Approved_Amount] [float] NULL,
[Chq_No] [varchar](50) NULL,
[Chq_dated] [datetime] NULL,
[Chq_Bank] [varchar](40) NULL,
[Chq_Amount] [float] NULL,
[Vendor_MKey] [int] NULL,
[Vendor_Comp_Mkey] [int] NULL,
[Project_Mkey] [numeric](10, 0) NULL,
[Program_mkey] [numeric](10, 0) NULL,
[Payment_MKey] [int] NULL,
[Due_Date] [datetime] NULL,
[Updated_Remarks] [varchar](500) NULL,
[Updated_Bill_no] [varchar](27) NULL,
[Updated_Bill_Date] [datetime] NULL,
[Updated_Bill_Amt] [float] NULL,
[Party_Name] [varchar](80) NULL,
[Acc_mkey] [numeric](10, 0) NULL,
[TotalDeductions] [float] NULL,
[Broker_Mkey] [numeric](10, 0) NULL,
[Customer_Mkey] [numeric](10, 0) NULL,
[Payable_Amt] [float] NULL,
[Balance_Amt] [float] NULL,
[Receipt_No] [varchar](50) NULL,
[Po_No] [varchar](50) NULL,
[Bill_No] [varchar](50) NULL,
[Oracle_doc_no] [varchar](100) NULL,
CONSTRAINT [PK_Inward_Doc_Tracking_Trl_1] PRIMARY KEY CLUSTERED
(
[Mkey] ASC,
[Entry_Sr_No] 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].[Inward_Doc_Tracking_Trl] ADD CONSTRAINT [DF_Inward_Doc_Tracking_Trl_U_Datetime] DEFAULT (getdate()) FOR [U_Datetime]
GO
ALTER TABLE [dbo].[Inward_Doc_Tracking_Trl] ADD CONSTRAINT [DF__Inward_Do__Delet__47FED732] DEFAULT ('N') FOR [Delete_Flag]
GO
You are inserting character values in [NStatus_Flag] and [CStatus_Flag] , Just change their data type in table or insert data with numeric value into them.
Well - one obvious error is that you have [CStatus_Flag] [numeric](8, 0) but select 'F' [CStatus_Flag].
Also just for clarity sake, but you shouldn't write '1' for selection of numeric fields either, when 1 can do it without conversions.

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.

SQL query taking 1 minute and 35 seconds

I am executing the query on SQL server on hosting and it is taking 1 minute and 35 seconds. And the no, of rows of retrieval are 18000. Still it is taking too much time. Query is
select ID,
FirstName,
LastName,
Branch,
EnquiryID,
Course,
College,
Mobile,
ExamID,
EntranceID,
Entrance,
Venue,
RegNo,
VenueID,
Exam,
Gender,
row_number() over (partition by EnquiryID order by ID asc) as AttemptNO
from AGAM_View_AOPList
order by EnquiryID
TABLE SCHEMAS
CREATE TABLE [dbo].[AGAM_AceOFPace](
[ID] [int] IDENTITY(1,1) NOT NULL,
[EnquiryID] [int] NULL,
[FirstName] [nvarchar](100) NULL,
[MiddleName] [nvarchar](100) NULL,
[LastName] [nvarchar](100) NULL,
[BranchID] [int] NULL,
[Branch] [nvarchar](100) NULL,
[CourseID] [int] NULL,
[ExamID] [int] NULL,
[Exam] [nvarchar](200) NULL,
[EntranceID] [int] NULL,
[Entrance] [nvarchar](200) NULL,
[RegNo] [nvarchar](200) NULL,
[EntranceCode] [nvarchar](100) NULL,
[ExamDate] [nvarchar](50) NULL,
[UserID] [nvarchar](100) NULL,
[EntranceFees] [numeric](18, 2) NULL,
[VenueID] [int] NULL,
[Venue] [nvarchar](max) NULL,
[ChequeNumber] [nvarchar](50) NULL,
[Bank] [nvarchar](100) NULL,
[CreatedDate] [datetime] NULL,
CONSTRAINT [PK_AGAM_AceOFPace] PRIMARY KEY CLUSTERED
(
[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]
GO
ALTER TABLE [dbo].[AGAM_AceOFPace] WITH CHECK ADD CONSTRAINT [FK_AGAM_AceOFPace_AGAM_Inquiry] FOREIGN KEY([EnquiryID])
REFERENCES [dbo].[AGAM_Inquiry] ([ID])
GO
ALTER TABLE [dbo].[AGAM_AceOFPace] CHECK CONSTRAINT [FK_AGAM_AceOFPace_AGAM_Inquiry]
GO
SECOND TABLE
CREATE TABLE [dbo].[AGAM_Inquiry](
[ID] [int] IDENTITY(1,1) NOT NULL,
[RegNo] [nvarchar](200) NULL,
[BranchID] [int] NULL,
[Category] [nvarchar](100) NULL,
[CourseID] [int] NULL,
[EntranceFees] [numeric](18, 2) NULL,
[EntranceID] [int] NULL,
[UserID] [nvarchar](50) NULL,
[Status] [nvarchar](50) NULL,
[ReminderDate] [datetime] NULL,
[Reminder] [nvarchar](150) NULL,
[Mobile] [nvarchar](50) NULL,
[Email] [nvarchar](50) NULL,
[FirstName] [nvarchar](50) NULL,
[MiddleName] [nvarchar](50) NULL,
[LastName] [nvarchar](50) NULL,
[Landline] [nvarchar](50) NULL,
[Address] [nvarchar](100) NULL,
[DOB] [datetime] NULL,
[Gender] [nvarchar](50) NULL,
[PfBatchTime] [nvarchar](50) NULL,
[SourceOfInquiry] [nvarchar](50) NULL,
[ExStudentID] [int] NULL,
[InquiryDate] [datetime] NULL,
[ReceiptNumber] [nvarchar](50) NULL,
[RawID] [int] NULL,
[Deleted] [int] NULL,
[CreatedBy] [nvarchar](50) NULL,
[CreatedDate] [datetime] NULL,
[LastModifiedBy] [nvarchar](50) NULL,
[LastModifiedDate] [datetime] NULL,
[College] [nvarchar](150) NULL,
[Qualification] [nvarchar](150) NULL,
[RptNo] [nvarchar](100) NULL,
CONSTRAINT [PK_AGAM_Inquiry] PRIMARY KEY CLUSTERED
(
[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]
GO
ALTER TABLE [dbo].[AGAM_Inquiry] WITH CHECK ADD CONSTRAINT [FK_AGAM_Inquiry_AGAM_Branch] FOREIGN KEY([BranchID])
REFERENCES [dbo].[AGAM_Branch] ([ID])
GO
ALTER TABLE [dbo].[AGAM_Inquiry] CHECK CONSTRAINT [FK_AGAM_Inquiry_AGAM_Branch]
GO
ALTER TABLE [dbo].[AGAM_Inquiry] WITH CHECK ADD CONSTRAINT [FK_AGAM_Inquiry_AGAM_Course] FOREIGN KEY([CourseID])
REFERENCES [dbo].[AGAM_Course] ([ID])
GO
ALTER TABLE [dbo].[AGAM_Inquiry] CHECK CONSTRAINT [FK_AGAM_Inquiry_AGAM_Course]
GO
ALTER TABLE [dbo].[AGAM_Inquiry] WITH CHECK ADD CONSTRAINT [FK_AGAM_Inquiry_AGAM_Users] FOREIGN KEY([UserID])
REFERENCES [dbo].[AGAM_Users] ([UserID])
GO
ALTER TABLE [dbo].[AGAM_Inquiry] CHECK CONSTRAINT [FK_AGAM_Inquiry_AGAM_Users]
GO
Can you try with changing the view to this?
SELECT TOP (100) PERCENT
AP.ID,
AP.FirstName,
AP.LastName,
AP.Branch,
AP.EnquiryID,
AC.Name,
AI.College,
AI.Mobile,
AP.ExamID,
AP.EntranceID,
AP.RegNo,
AP.VenueID,
AP.Exam,
AI.Gender,
AP.BranchID,
AP.CourseID,
AP.CreatedDate,
AI.Status,
AP.Entrance,
AP.Venue
FROM dbo.AGAM_AceOFPace AS AP
INNER JOIN dbo.AGAM_Inquiry AS AI ON AI.ID = AP.EnquiryID
INNER JOIN dbo.AGAM_Course as AC on AC.ID = AP.CourseId
ORDER BY AP.EnquiryID
Do you have an index on EnquiryId and CourseID?
Seeing as you are joining, ordering and partitioning by it you really should.
CREATE INDEX IDX_AGAM_AceOFPace_EnquiryID
ON AGAM_AceOFPace (EnquiryID)
CREATE INDEX IDX_AGAM_AceOFPace_CourseID
ON AGAM_AceOFPace (CourseID)

Conversion failed when converting from a character string to uniqueidentifier - why?

I am getting this error when running:
SELECT *
FROM repsresidents rr
LEFT JOIN
(SELECT *
FROM residents r1
INNER JOIN
(SELECT res_peopleidy AS peopleidy,
min(res_id) AS RES_ID2
FROM residents
WHERE res_active = '1'
GROUP BY res_peopleidy) r2 ON r1.res_id = r2.res_id2) r ON rr.mainpeopleidy = r.res_peopleidy
WHERE rr.communityidy = 1
I believe the problem is on min(res_id) AS RES_ID2 because res_id is a PK.
Here's the schema of residents table
CREATE TABLE [dbo].[Residents](
[RES_ID] [int] IDENTITY(1,1) NOT NULL,
[RES_PeopleIDY] [varchar](50) NOT NULL,
[RES_PhyMoveInDate] [datetime] NULL,
[RES_CurrentUnitNumber] [varchar](50) NULL,
[RES_CommunityIDY] [int] NULL,
[RES_DateStarted] [datetime] NULL,
[RES_NoPart] [int] NULL,
[RES_LastUserUpdated] [int] NULL,
[PER_ID] [int] NULL,
[HEA_ID] [int] NULL,
[LIF_ID] [int] NULL,
[INT_ID] [int] NULL,
[TES_ID] [int] NULL,
[STA_ID] [int] NULL,
[STA_Type] [int] NULL,
[NetworkSet] [int] NULL,
[RES_Active] [int] NULL,
[RES_HasImage] [int] NULL,
[RES_UpdatedImage] [int] NULL,
[RES_Bio] [text] NULL,
[RES_BioUpdate] [datetime] NULL,
[RES_BioUpdateBy] [int] NULL,
[ACT_ID] [int] NULL,
[RES_LobbyBio] [varchar](max) NULL,
[RES_LobbyBioUpdate] [datetime] NULL,
[RES_LobbyBioUpdateBy] [int] NULL,
[RES_DiscNotes1] [varchar](max) NULL,
[RES_DiscNotes2] [varchar](max) NULL,
[RES_DiscNotes3] [varchar](max) NULL,
[RES_DiscNotes4] [varchar](max) NULL,
[RES_DiscNotes5] [varchar](max) NULL,
[RES_ExpiredDate] [datetime] NULL,
[RES_ExpiredUser] [int] NULL,
[RES_FinishedDate] [datetime] NULL,
[RES_TasksSet] [int] NULL,
CONSTRAINT [PK_Residents] PRIMARY KEY CLUSTERED
(
[RES_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]
What am I doing wrong?
Since there are no UNIQUEIDENTIFIERS on Residents, I would have to believe that your issue is with RepsResidents. Any chance that mainpeopleidy is a uniqueidentifier?