I don't know anything about procedure, but I have to create one so I tried one. But now I am getting error - please help.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Get_List_Docter_Detail_A]
#special varchar(MAX),
#city varchar(MAX),
#offset int,
#pageSet int,
#area varchar(MAX)
AS
Begin
declare #sql nvarchar(MAX);
set #sql = 'SELECT'+
'(SELECT Stuff('+
'(SELECT N"," + sp.specialization FROM DSpecialization_Master dsp'+
'LEFT JOIN Specialization_Master sp on sp.id = dsp.specialization'+
'WHERE dsp.profileid = pm.id and (dsp.specialization = (select id from Specialization_master where specialization='+#special+'))'+
'FOR XML PATH(""),TYPE)'+
'.value("text()[1]","nvarchar(max)"),1,1,N"")) as drspec,'+
'pm.id as profileid,'+
'pm.loginid as loginid,'+
'dam.clinicname,'+
'dam.area,'+
'dam.address,'+
'dam.pincode,'+
'dam.id as addressid,'+
'dam.feecharge as feecharge,'+
'pm.fname,'+
'pm.lname,'+
'pm.email,'+
'pm.mobile,'+
'pm.phone,'+
'pm.gender,'+
'pm.dob,'+
'pm.totexp,'+
'pm.imagepath,'+
'pm.languages,'+
'pm.statement,'+
'pm.createdby,'+
'convert(nvarchar, pm.createdon, 103) as createddate,'+
'convert(nvarchar, pm.createdon, 108) as createdtime,'+
'pm.hsbit,'+
'overall_count = COUNT(*) OVER(),'+
'(SELECT Stuff('+
'(SELECT N"," + education FROM DEducation_Master WHERE profileid = pm.id'+
'FOR XML PATH(""),TYPE)'+
'.value("text()[1]","nvarchar(max)"),1,1,N"")) as dredu'+
'FROM Profile_Master pm '+
'LEFT JOIN DAddress_Master dam on dam.profileid = pm.id '+
'WHERE '+
'dam.city='+#city;
if #area!=''
set #sql+=' and dam.area in('+#area+') and';
set #sql+=' pm.id IN (SELECT profileid FROM DSpecialization_Master WHERE specialization = (select id from Specialization_master where specialization='+#special+')) ORDER BY dam.city OFFSET '+#offset+' ROWS FETCH NEXT '+#pageSet+' ROWS ONLY';
EXECUTE sp_executesql #sql
END
I am getting this error.
Msg 245, Level 16, State 1, Procedure Get_List_Docter_Detail_A, Line 61
Conversion failed when converting the nvarchar value 'SELECT(SELECT Stuff((SELECT N"," + sp.specialization FROM DSpecialization_Master dspLEFT JOIN Specialization_Master sp on sp.id = dsp.specializationWHERE dsp.profileid = pm.id and (dsp.specialization = (select id from Specialization_master where specialization=Dentist))FOR XML PATH(""),TYPE).value("text()[1]","nvarchar(max)"),1,1,N"")) as drspec,pm.id as profileid,pm.loginid as loginid,dam.clinicname,dam.area,dam.address,dam.pincode,dam.id as addressid,dam.feecharge as feecharge,pm.fname,pm.lname,pm.email,pm.mobile,pm.phone,pm.gender,pm.dob,pm.totexp,pm.imagepath,pm.languages,pm.statement,pm.createdby,convert(nvarchar, pm.createdon, 103) as createddate,convert(nvarchar, pm.createdon, 108) as createdtime,pm.hsbit,overall_count = COUNT(*) OVER(),(SELECT Stuff((SELECT N"," + education FROM DEducation_Master WHERE profileid = pm.idFOR XML PATH(""),TYPE).value("text()[1]","nvarchar(max)"),1,1,N"")) as dreduFROM Profile_Master pm LEFT JOIN DAddress_Master dam on dam.profileid = pm.id WHERE dam.city=surat and dam.area in(Adajan) and' to data type int.
What am I doing wrong? Please correct me.
Try to replace double quotas with double single quotas
Replace this line
'(SELECT N"," + sp.specialization
With
'(SELECT N'','' + sp.specialization
Related
I have a query that sends an email to me each month for the previous month's data that we receive. I'd like to include the last month and current year in the filename. I got the month and year to work but when I try to show them in the filename, SQL tries to escape the line because I'm using a forward slash to separate month and year.
For example, the code below returns "2021.csv" as the filename. How do I use a forward slash in the filename?
SELECT #query_attachment_filename =
N'SITLAMonthlyEntityReport'
+N' '
+CAST(DATEPART(MONTH, DATEADD(MONTH, -1, GETDATE())) AS NVARCHAR(12))
+N'/' -- This is the problem area.
+CAST(YEAR(GETDATE()) AS NVARCHAR(4))
+N'.csv';
I've tried using all of these methods without luck:
N''/'' -- I get, "Operand data type nvarchar is invalid for divide operator".
''/'' -- I get, "Operand data type varchar is invalid for divide operator".
['/']
/ -- I get, "Incorrect syntax near '/'".
I'd like to see this as an example filename: "SITLAMonthlyEntityReport 9/2021".
EDIT: I was asked for the entire query that included the snippet from above. Below is the full query, minus email information.
BEGIN
DECLARE #message NVARCHAR(1000);
DECLARE #subject NVARCHAR(100);
DECLARE #query NVARCHAR(MAX);
DECLARE #tab NCHAR(1) = NCHAR(9);
DECLARE #query_attachment_filename NVARCHAR(520);
DECLARE #CRLF NCHAR(2);
SELECT #CRLF = NCHAR(13)+NCHAR(10)
SELECT #subject = 'Well Information Report'
SELECT #message = N'Dear ###, '
+#CRLF+ N''
+#CRLF+ N'Please refer to the attached spread sheet for the results of last month''s information report ('
+CAST(DATEPART(MONTH, DATEADD(MONTH, -1, GETDATE())) AS NVARCHAR(12))
+N'/'
+CAST(YEAR(GETDATE()) AS NVARCHAR(4))
+N').'
+#CRLF+ N''
+#CRLF+ N'If there aren''t any results in the attached CSV, the query didn''t find any information for the last month,'
+#CRLF+ N''
+#CRLF+ N'Thanks,'
+#CRLF+ N'###';
SELECT #query =
'
SET NOCOUNT ON;
--DECLARE #SearchYear AS NVARCHAR(4) = YEAR(GETDATE())
--DECLARE #SearchMonth AS NVARCHAR(9) = DATEPART(MONTH, DATEADD(MONTH, -1, GETDATE()))
DECLARE #SearchYear AS NVARCHAR(4) = 2021
DECLARE #SearchMonth AS NVARCHAR(9) = 7
SELECT
API14,
[Entity Number],
[First Prod Date],
[Spacing Rule],
TPI AS [Top Producing Interval Location],
BH AS [Bottom Hole Location],
[Well History Comments],
[Well History Modify Date] AS [Last Modified Date]
FROM
(
SELECT
dbo.BuildAPI14(Well.WellID, Construct.SideTrack, Construct.Completion) AS [API14],
CAST(ConstructDate.EventDate AS DATE) AS [First Prod Date],
Loc.LocType AS [Location Type],
CONCAT(''Township '',LocExt.Township,LocExt.TownshipDir,'' '',''Range '',LocExt.Range,LocExt.RangeDir,'' Section '',LocExt.Sec,'' '',RefCounty.CountyName,'' County'') AS ''Location'',
tblAPDTracker.SpacingRule AS [Spacing Rule],
Lease.Number AS [Entity Number],
WellHistory.WHComments AS [Well History Comments],
WellHistory.ModifyDate AS [Well History Modify Date]
FROM dbo.Well
LEFT JOIN dbo.tblAPDTracker ON LEFT(tblAPDTracker.APINO,10) = Well.WellID
LEFT JOIN dbo.Construct ON Construct.WellKey = Well.PKey
LEFT JOIN dbo.ConstructReservoir ON ConstructReservoir.ConstructKey = Construct.PKey
LEFT JOIN dbo.Lease ON Lease.Pkey = ConstructReservoir.LeaseKey
LEFT JOIN dbo.WellHistory ON WellHistory.WellKey = Construct.WellKey
LEFT JOIN dbo.ConstructDate ON ConstructDate.ConstructKey = Construct.PKey AND ConstructDate.Event = ''FirstProduction''
LEFT JOIN dbo.Loc ON loc.ConstructKey = Construct.PKey AND Loc.LocType IN (''BH'',''TPI'')
LEFT JOIN dbo.LocExt ON LocExt.LocKey = Loc.PKey
LEFT JOIN dbo.RefCounty ON RefCounty.PKey = LocExt.County
WHERE
WellHistory.WorkType = ''ENTITY''
AND WellHistory.ModifyUser = ''UTAH\###''
AND YEAR(WellHistory.ModifyDate) = #SearchYear
AND MONTH(WellHistory.ModifyDate) = #SearchMonth
GROUP BY
Well.WellID,
Construct.SideTrack,
Construct.Completion,
ConstructDate.EventDate,
Loc.LocType,
LocExt.Township,
LocExt.TownshipDir,
LocExt.Range,
LocExt.RangeDir,
LocExt.Sec,
RefCounty.CountyName,
tblAPDTracker.SpacingRule,
Lease.Number,
WellHistory.WHComments,
WellHistory.ModifyDate
) AS BasicQuery
PIVOT
(
MIN(BasicQuery.Location) FOR [Location Type] IN ([TPI], [BH])
) AS PivotedQuery
ORDER BY
API14,
[Well History Modify Date];
'
SELECT #query_attachment_filename = N'SITLAMonthlyEntityReport'
+N' '
+CAST(DATEPART(MONTH, DATEADD(MONTH, -1, GETDATE())) AS NVARCHAR(12))
+'/'
+CAST(YEAR(GETDATE()) AS NVARCHAR(4))
+N'.csv';
EXEC msdb.dbo.sp_send_dbmail
#profile_name = '###',
#from_address = '###',
#recipients = '###',
#reply_to = '###',
#body = #message,
#query = #query,
#query_attachment_filename = #query_attachment_filename,
#attach_query_result_as_file = 1,
#query_result_header = 1,
#query_result_width = 32767,
#query_result_separator = #tab,
#append_query_error = 0,
#execute_query_database = 'UTRBDMSNET'
END
I need to append below select query set with another set query based on condition
DECLARE #queryString VARCHAR(1000);
-- Insert statements for procedure here
Set #queryString ='SELECT
CASE
WHEN d.sno IS NOT NULL THEN 'y'
ELSE NULL
END
amendment_type,
u.user_login_id [User],
role_name [Role],
u.user_name [Name],
a.companyname +':<br>('+b.branch+')' [Agent/Branch],
u.last_login_pc+'('+u.ip_address+')<br> Login Time: '+cast(u.last_login AS varchar(50)) [Last Login],
u.lock_status [Lock/Unlock],
CASE
WHEN u.lock_status='y' THEN 'Locked - '+ u.lock_by
WHEN datediff(d,u.last_login,getdate())>u.lock_days
AND isnull(u.lock_days,0)>0 THEN 'Locked - Day Exceed'
WHEN u.active_session IS NULL
AND isnull(u.lock_status,'n')='n' THEN 'Not Login'
ELSE 'Active'
END
[Status],
u.*,
a.agentcan,
b.branch,
b.branchcodechar,
NULL branchcan
FROM agentsub u
JOIN agentbranchdetail b
ON u.agent_branch_code=b.agent_branch_code
JOIN agentdetail a
ON b.agentcode=a.agentcode
LEFT OUTER JOIN application_role_agent_user r
ON u.user_login_id=r.user_id
LEFT OUTER JOIN application_role p
ON r.role_id=p.role_id
LEFT OUTER JOIN agentsub_amendment d
ON d.agent_user_id=u.agent_user_id
WHERE 1=1'
IF (#loginId !=null)
BEGIN
SET #queryString =#queryString + 'and u.user_login_id like ('+ #loginId +')'
END
SET #queryString =#queryString +'order by u.user_login_id,a.companyname,b.branch'
EXEC #queryString
First... Your query as it stands (via notepad++) is 1,731 characters, so it wont fit into a varchar(1000)
Second... You need to address some escaping issues with your query; e.g.
WHEN d.sno IS NOT NULL THEN 'y'
should probably be
WHEN d.sno IS NOT NULL THEN ''y''
Third... google/investigate sp_executesql and parameters
Finally... as #Panagiotis Kanavos says, Don't concatenate anything (see Third...); you need to look up "sql injection"
#uberbloke is correct regarding query length.
EXEC sp_executesql with multiple parameters link give you solution for dynamic query to pass parameter values.
Please check below updated query code.
DECLARE #queryString NVARCHAR(MAX);
-- Insert statements for procedure here
Set #queryString =
'SELECT
CASE
WHEN d.sno IS NOT NULL THEN ''y''
ELSE NULL
END
amendment_type,
u.user_login_id [User],
role_name [Role],
u.user_name [Name],
a.companyname + '':<br>('' + b.branch) [Agent/Branch],
u.last_login_pc + ''('' + u.ip_address + '')<br> Login Time: '' + cast(u.last_login AS varchar(50)) + '' [Last Login],
u.lock_status [Lock/Unlock],
CASE
WHEN u.lock_status = ''y'' THEN ''Locked - '' + u.lock_by
WHEN datediff(d,u.last_login,getdate()) > u.lock_days AND (u.lock_days,0) > 0 THEN ''Locked - Day Exceed''
WHEN u.active_session IS NULL AND isnull(u.lock_status,''n'') = ''n'' THEN ''Not Login''
ELSE ''Active''
END [Status],
u.*,
a.agentcan,
b.branch,
b.branchcodechar,
NULL branchcan
FROM agentsub u
JOIN agentbranchdetail b ON u.agent_branch_code = b.agent_branch_code
JOIN agentdetail a ON b.agentcode = a.agentcode
LEFT OUTER JOIN application_role_agent_user r ON u.user_login_id = r.user_id
LEFT OUTER JOIN application_role p ON r.role_id = p.role_id
LEFT OUTER JOIN agentsub_amendment d ON d.agent_user_id = u.agent_user_id
WHERE 1 = 1 '
IF (#loginId !=null)
BEGIN
SET #queryString = #queryString + 'and u.user_login_id like ('+ #loginId + ')'
END
SET #queryString = #queryString + ' order by u.user_login_id,a.companyname,b.branch'
EXEC sp_executesql #queryString
I am getting below error:
I am trying to execute sp_executesql inside a stored procedure. When I execute the stored procedure, it throws this following error
Msg 8114, Level 16, State 5, Line 0
Error converting data type varchar to int
I couldn't figure it out where the error occurs
Here is my stored procedure
ALTER PROCEDURE [dbo].[spHoldTransaction]
#RegisterNo INT,
#StoreID INT,
#Department VARCHAR(50),
#TransactionDateFrom DATE,
#TransactionDateTo DATE,
#Comment VARCHAR(50)
AS
BEGIN
DECLARE #DatabaseName VARCHAR(15);
IF (#StoreID = 5555)
BEGIN
SET #DatabaseName = 'xxx'
END
SET #Department=''''+REPLACE(#Department,',',''',''')+''''
DECLARE #HoldEntryQry NVARCHAR(MAX);
DECLARE #HoldEntryParamDefinition NVARCHAR(MAX);
SET #HoldEntryParamDefinition = N'#Department VARCHAR(50),#StoreID INT,#NewId INT,#TransactionDateFrom DATETIME,#TransactionDateTo DATETIME'
DECLARE #NewId INT;
SET #NewID = 15;
SET #HoldEntryQry = 'SELECT te.StoreID, ' + CONVERT(VARCHAR(MAX), #NewId) + ' AS TransactionHoldID,
te.ItemLookupCode,
item.Description,
te.ItemID,
SUM(te.Quantity) Quantity,
SUM(te.SalesTax) Tax,
SUM(te.Price * te.Quantity) Value,
SUM(te.Price * te.Quantity) / SUM(te.Quantity) Price,
item.price FullPrice,
--1 AS Taxable,
GETDATE() AS TransactionTime,
''1899-12-30'' AS VoucherExpirationDate
FROM
TransactionEntry te
LEFT JOIN
item ON item.id = te.ItemID
INNER JOIN
item nItem ON nitem.ItemLookupCode = item.itemlookupcode
WHERE
te.TransactionDate >= ''' + CONVERT(VARCHAR, CAST(#TransactionDateFrom AS DATE), 102) +
''' AND te.TransactionDate <= ''' +
CONVERT(VARCHAR, CAST(#TransactionDateTo AS DATE), 102) +
''' AND item.department IN (' + #Department + ')
AND te.storeid = ' + convert(varchar(max), #StoreID)+'
group by
te.StoreID,
te.ItemLookupCode,
item.Description,
te.ItemID,
item.price
'
EXECUTE sp_executesql #HoldEntryQry, #HoldEntryParamDefinition, #NewId, #Department, #Storeid,#TransactionDateFrom, #TransactionDateTo
END
When I do Print #HoldEntryQry, the query looking like below
select
te.StoreID,
15 AS TransactionHoldID,
te.ItemLookupCode,
item.Description,
te.ItemID,
sum(te.Quantity) Quantity,
sum(te.SalesTax) Tax,
sum(te.Price * te.Quantity) Value,
sum(te.Price * te.Quantity)/sum(te.Quantity) Price,
item.price FullPrice,
1 AS Taxable,
Getdate() AS TransactionTime,
'1899-12-30' AS VoucherExpirationDate
from
TransactionEntry te
left join item on item.id = te.ItemID
inner join item nItem on nitem.ItemLookupCode = item.itemlookupcode
where
te.TransactionDate >= '2018.04.16' and te.TransactionDate <='2018.04.30' and item.department in ('Apple','Orange','Dates') and te.storeid = 5555
group by
te.StoreID,
te.ItemLookupCode,
item.Description,
te.ItemID,
item.price
The printed query is returning the exact result I expect
The problem is probably +#Department+. If any argument to + is not a string, you are probably going to get a conversion error.
But don't just do cast(#department as varchar(255)). Fix the root cause of the problem. You already know about parameters. Use them for all the constants in the where clause! This will make your debugging easier.
My code is like this
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
ALTER PROCEDURE [dbo].[getprocbyproc]
#flg varchar(2),
#qaaprvdt char(8),
#dbo varchar(20),
#plantid char(1)
AS
DECLARE #dynamicSQL varchar(8000)
DECLARE #datemth char(6)
DECLARE #dateday char(2)
DECLARE #FXTIME char(4)
DECLARE #TBL varchar(20)
DECLARE #def varchar(20)
DECLARE #OUTDAT CHAR(20)
SET #datemth = substring(#qaaprvdt,1,6)
SET #dateday = substring(#qaaprvdt,7,2)
IF #flg = 'QA' AND #dbo = 'PRCDAILYQA'
BEGIN
SET #TBL = 'DAILYQA'
SET #OUTDAT = 'CO.QAAPRVDT'
END
IF #plantid = '1'
BEGIN
SET #def = "SQDPRCDEF1"
END
IF #flg = 'QA' AND #plantid = '1'
BEGIN
SET #dynamicSQL = 'insert into PrcdailyQA' +
'(process, seqno, qaamon, qaaday, orderno,
ingotno, theopcs, cwacc, pwacc, pwout,
procyld, prodyld, plantid, prodline) ' +
'(SELECT distinct(b.PROCNO), b.proseq, "' +
#datemth + '" , "' + #dateday +
'", a.orderno, a.ingotno, a.theopcs, a.cwacc, a.pwacc, a.pwout, a.COprocyld, a.COprodyld, a.plantid, a.prodline ' +
'FROM DailyQA a , SQDPRCDEF1 b ' +
'WHERE a.qaamon = ' + #datemth + ' and a.qaaday= ' + #DATEDAY + ' and a.plantid="1"' +
'GROUP BY b.procno, b.proseq, a.orderno, a.ingotno, a.theopcs, a.cwacc, a.pwacc, a.pwout, a.COprocyld, a.COprodyld, a.plantid, a.prodline) '
Now when I to execute it returns no error. But when I try to execute it at runtime, it returns error
Msg 164, Level 15, State 1, Line 1
Each GROUP BY expression must contain at least one column that is not an outer reference.
I already refer this http://www.sql-server-performance.com/2007/group-by-expression-contain-one-column-not-an-outer-reference/ and try to change the group by statement, also return error.
Please help!
Because you are not aggregating on any fields (i.e. using sum, max, etc.), you don't really need to use a group by clause in your example.
However, what are you trying to do in the from clause? You are currently creating a cartesian product of the 2 tables -- you aren't joining the tables on any common field.
Without knowing more, I'd be more inclined to remove the group by clause altogether, and have something like this:
insert into ...
select distinct b.PROCNO, b.proseq, ...
from ...
where ...
Btw, in general I wouldn't recommend using commas in a from clause, use join instead.
You don't need DISTINCT in a GROUP BY query. Also, you are selecting columns which do not either appear in the GROUP BY clause or are aggregates of columns. Removing DISTINCT along with the non-aggregate columns would leave you with the following query:
INSERT INTO PrcdailyQA (process, seqno, qaamon, qaaday, orderno, ingotno, theopcs, cwacc,
pwacc, pwout, procyld, prodyld, plantid, prodline)
SELECT b.PROCNO, b.proseq, a.orderno, a.ingotno, a.theopcs, a.cwacc, a.pwacc, a.pwout,
a.COprocyld, a.COprodyld, a.plantid, a.prodline
FROM DailyQA a, SQDPRCDEF1 b
WHERE a.qaamon = ' + #datemth + ' AND a.qaaday = ' + #DATEDAY + ' AND a.plantid = "1"'
GROUP BY b.procno, b.proseq, a.orderno, a.ingotno, a.theopcs, a.cwacc, a.pwacc, a.pwout,
a.COprocyld, a.COprodyld, a.plantid, a.prodline
I believe there are many StackOverflow posts related to this error, but none seems to have a straightforward solution which I am looking for. I'll be thankful if anyone of you can look into this.
The issue: I am using a dynamic sql stored procedure which uses FundTransfer Database tables in cte expression and then joins with WebbnkDb database.
But, I run into the exception mentioned in the title above. Everything works fine if I remove WITH EXECUTE AS SELF command but unfortunately I can't get rid of it as it is used for some security reasons. Please suggest me solution in easy words.
USE [WebBank]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[usp_naSearchV2_20131504]
#Debug BIT = 0,
#UserName varchar(50)=NULL, --This will be used to potentially limit the results per user & also for logging
#SSN char(9) = NULL,
#FName varchar(25) = NULL,
#LName varchar(30) = NULL,
#dtApplicationStart datetime = NULL,
#dtApplicationEnd datetime = NULL,
#CompanyName varchar(50) = NULL,
#DaysInTask int = NULL, --This will be how many days it's been in the current task...
#AcctNum varchar(11) = NULL,
#BranchNums varchar(1500) = NULL, --This will be passed to an IN. Don't enclose each in single quotes - for example, '45, 145, 1, 15'
#WorkflowID int = NULL, --1 = HSA, 2 = Personal, 3 = SEI
#OriginationID tinyint = NULL, --This comes from the Applicant record.
#QueueID int = NULL,
#TaskStageIDs varchar(500) = NULL, --Will be passed to an IN, so multiple TaskStageIDs can be passed.
#TaskIDs VARCHAR(1500)=NULL,
#DaysAged int = NULL, --Days since application was entered (not including time spent in approved/declined/open states)
#LastActivityStart datetime=NULL,
#LastActivityEnd datetime=NULL,
#SOAApplID int = NULL, --SEI ID
#Market VARCHAR(50) = NULL, --from luAffinityMarket
#IncludeSecondary bit=0,
#IncludeAliasName bit=0,
#EmailTypeIDs varchar(500) = NULL
WITH EXECUTE AS SELF --This is needed because we're using dynamic SQL & don't want to grant access to underlying tables.
AS
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
/*
** New Account - Search.
**
** This will be done in dynamic SQL. The reason is because when searching on multiple optional parameters,
** SQL cannot use indexes without using dynamic SQL. This makes the proc sssssslllllooooooooowwwwwwwwwww (when not using dynamic sql).
** See http://www.sommarskog.se/dyn-search-2005.html
**
** In addition to the basics (name, social, branch, product, "workflow"), also show Task, Queue, Check-Out info, etc
**
*/
/*
I have to create new version of this store procedure since we continue making changes to resolve helpdesk tickets and
for AOT Part 2. Some tables that we are going to use for AOT project part 2 will not be moved to production until 12/05/10.
New version will be called usp_naSearchV2 and will contain new tables for AOT Part 2
*/
--CAST(ROUND(ISNULL(cteAge.Age + 1, 0), 2) AS DECIMAL(8, 2)) AS DaysAged,
DECLARE #SQL nvarchar(max),#paramlist nvarchar(max)
DECLARE #SOASQL nvarchar(MAX)
SET #FName = '%' + #FName + '%'
SET #LName = '%' + #LName + '%'
SET #CompanyName = '%' + #CompanyName + '%'
SELECT #SQL = '
WITH
cteAutoApprove (AcctID, AutoApproved)
AS (
SELECT awt.AcctID, MIN(CAST(awt.autoEnter AS SMALLINT)) AS AutoApproved
FROM dbo.AccountWorkflowTask awt JOIN dbo.WorkflowTask wt ON awt.WorkflowTaskID = wt.WorkflowTaskID
WHERE (wt.TaskID IN (9, 17) AND ReasonIDExit = 1)
OR (wt.TaskID IN (209, 309, 409, 509, 609, 709, 809, 909) AND ReasonIDExit = 40)
--OR ReasonIDExit IN(216,202) OR ReasonIDEnter=215
or(wt.TaskID=201 and ReasonIDExit is NULL) GROUP BY awt.AcctID),
cteAge (AcctID, Age)
AS (SELECT AcctID, SUM(CASE WHEN t.TaskStageID IN (2, 3, 4) OR t.TaskID = 1 THEN 0 '--don''t count Pending Completion, Open, Approved, or Declined in age
+ 'ELSE DATEDIFF(minute, dtEnter, ISNULL(dtExit, GETDATE())) END) / 60 / 24.0 Age
FROM dbo.AccountWorkflowTask awt JOIN WorkflowTask wt ON awt.WorkflowTaskID = wt.WorkflowTaskID JOIN Task t ON wt.TaskID = t.TaskID
GROUP BY AcctID),
**cteFundingStatus(AcctID,FundingStatus,SourceAccountTypeDescription)
AS
(SELECT TransferStaging.AcctID,luTransferStatus.TransferStatusDesc, luAcctType.AcctTypeDesc from
FundsTransfer.dbo.TransferStaging
JOIN FundsTransfer.dbo.luTransferType ON luTransferType.TransferTypeID = TransferStaging.TransferTypeID
JOIN FundsTransfer.dbo.luAcctType ON luTransferType.SourceAcctTypeID = luAcctType.AcctTypeID
JOIN FundsTransfer.dbo.luTransferStatus ON luTransferStatus.TransferStatusID = TransferStaging.TransferStatusID),**
cteFulfillment(AcctID, Request, TemplateName)
AS
(SELECT ful.AcctID, CAST(Request AS NVARCHAR(max))Request, lt.TemplateName FROM dbo.fulfillment ful left join LetterRequest lr on lr.LetterID = ful.LetterID
LEFT JOIN luLetterTemplate lt ON lt.TemplateID = lr.TemplateID
WHERE (Request IS NOT NULL OR ful.LetterID IS NOT NULL) AND FulfillmentID=(SELECT MAX(FulfillmentID) FROM fulfillment sub WHERE ful.AcctID=sub.AcctID AND (Request IS NOT NULL OR LetterID IS NOT NULL)) ),
cteNote(AcctID,userEntered,dtEntered,Note,NoteReasonDesc,ReasonCode,NoteReasonID)
as
(SELECT AcctID,userEntered,dtEntered,Note,NoteReasonDesc,ReasonCode,n.NoteReasonID FROM note n JOIN
dbo.luNoteReason lu ON lu.NoteReasonID=n.NoteReasonID WHERE '
IF #EmailTypeIDs IS NOT NULL
SELECT #SQL=#SQL+' n.NoteReasonID IN (' + #EmailTypeIDs + ') AND '
SELECT #SQL=#SQL+ ' dtEntered=(SELECT MAX(dtEntered)FROM note sub WHERE sub.AcctId=n.AcctID '
IF #EmailTypeIDs IS NOT NULL
SELECT #SQL=#SQL+ ' AND sub.NoteReasonID IN (' + #EmailTypeIDs + ')'
SELECT #SQL=#SQL+')) '
SELECT #SQL=#SQL+'SELECT a.ApplID, acct.AcctID, acct.dtApplication, ai.FName, ai.MName, ai.LName, ai.SSN, a.Email, ao.CompanyName,'
SELECT #SQL=#SQL+'ao.DBAName, ao.TaxID, acct.AcctNum, acct.AcctAffinityNum, luA.AffinityNum, luA.AffinityName, t.TaskDesc, awt.dtEnter,'
SELECT #SQL=#SQL+'DATEDIFF(day, awt.dtEnter, GETDATE()) + 1 DaysInTask, q.QueueDesc, w.WorkflowID, w.WorkflowDesc,'
SELECT #SQL=#SQL+'luO.OriginationID, luO.OriginationDesc, aco.dtCheckOut, aco.UserCheckOut, aco.GUIDCheckout, lts.TaskStageDesc,'
SELECT #SQL=#SQL+'DATEDIFF(day, acct.dtApplication, GETDATE()) + 1 DaysAgedOld,CAST(ROUND(ISNULL(cteAge.Age + 1, 0), 2) AS int) AS DaysAged,'
SELECT #SQL=#SQL+'asa.SOAApplID, case when (w.WorkflowID=1 and luO.OriginationID=4) then ''Low''when luO.OriginationID=9 then ''Low'''
SELECT #SQL=#SQL+'else''High'' end as RiskType, awt.userEnter, awt.dtEnter, case when cteAutoApprove.AutoApproved=1 then ''Automated'''
SELECT #SQL=#SQL+'when cteAutoApprove.AutoApproved=0 then ''Manual'' else '''' end as DecisionType,acctLam.Market,ful.Request,ful.TemplateName,fun.SourceAccountTypeDescription,fun.FundingStatus, acct.BrokerCode,
COALESCE(ai.SSN, ao.TAXID) as TIN, case when bup.BusPurposeDesc like ''%Other%'' then ao.BusPurposeOther else bup.BusPurposeDesc end as BusPurpose
,note.Note,note.NoteReasonDesc,note.ReasonCode,aa.RelationshipCode,luRel.RelationshipCodeDesc, Addr.Address1, Addr.Address2, Addr.City, Addr.State, Addr.Zip FROM dbo.Applicant a JOIN dbo.APPLICANTACCOUNT aa ON a.ApplID = aa.ApplID '
IF #IncludeSecondary=0
SELECT #SQL=#SQL+' AND aa.RelationshipCode = ''000'' '
SELECT #SQL=#SQL+'LEFT JOIN dbo.ApplicantIndiv ai ON a.ApplID = ai.ApplID LEFT JOIN dbo.ApplicantOrg ao ON a.ApplID = ao.ApplID JOIN dbo.AFFINITYGROUP ag ON a.AffGroupID = ag.AffGroupID JOIN dbo.luAffinity luA ON ag.AffinityID = luA.AffinityID
JOIN dbo.Account acct ON aa.AcctID = acct.AcctID JOIN dbo.AccountWorkflowTask awt ON acct.AcctID = awt.AcctID AND awt.dtExit IS NULL --join to current AccountWorkflowTask
JOIN dbo.WorkflowTask wt ON awt.WorkflowTaskID = wt.WorkflowTaskID JOIN dbo.Task t ON wt.TaskID = t.TaskID
JOIN dbo.Workflow w ON wt.WorkflowID = w.WorkflowID JOIN dbo.luTaskStage lts ON t.TaskStageID = lts.TaskStageID
LEFT JOIN dbo.Queue q ON t.QueueID = q.QueueID LEFT JOIN dbo.luOrigination luO on a.OriginationID = luO.OriginationID
LEFT JOIN dbo.accountCheckOut aco ON acct.AcctID = aco.AcctID AND aco.dtCheckIn IS NULL LEFT JOIN AccountSOAApplication asa ON acct.AcctID = asa.AcctID
LEFT JOIN cteAutoApprove on cteAutoApprove.AcctID = acct.AcctID LEFT JOIN cteAge ON cteAge.AcctID = acct.AcctID
LEFT JOIN luAffinityMarket lam ON CAST(luA.AffinityNum AS INT) = CAST(lam.BRNCH_NBR AS INT) LEFT JOIN luAffinityMarket acctLam ON acct.AcctAffinityNum = CAST(acctLam.BRNCH_NBR AS INT)
LEFT JOIN cteFulfillment ful on acct.AcctID=ful.AcctID
left Join **cteFundingStatus** fun on fun.AcctID=acct.AcctID
left Join luBusPurpose bup on bup.BusPurposeID=ao.BusPurposeID
Left join cteNote note on acct.AcctID=note.AcctID
left join luRelationshipCode luRel on aa.RelationshipCode=luRel.RelationshipCode
LEFT JOIN Address Addr ON Addr.ApplID = aa.ApplID AND Addr.AddrTypeID = 1
WHERE 1 = 1 ' --this is in here so that the following statements in the WHERE clause can start with "AND (...)".
-- IF #debug = 1 PRINT LEN(#SQL) v_AOTInitialAccountFunding
--SELECT #SQL = REPLACE(#SQL, CHAR(9), '') --remove tabs to save string size
IF #debug = 1 PRINT LEN(#SQL)
IF #SSN IS NOT NULL
SELECT #sql = #sql + ' AND (ai.SSN = #xSSN OR REPLACE(ao.TaxID, ''-'', '''') = #xSSN)'
IF #IncludeAliasName <>1 AND #FName IS NOT NULL
SELECT #sql = #sql + ' AND (ai.FName LIKE #xFName)'
IF #IncludeAliasName <>1 AND #LName IS NOT NULL
SELECT #sql = #sql + ' AND (ai.LName LIKE #xLName)'
IF #IncludeAliasName <>0 AND #FName IS NOT NULL
SELECT #sql = #sql + ' AND (ai.AliasFName LIKE #xFName OR ai.FName LIKE #xFName)'
IF #IncludeAliasName <>0 AND #LName IS NOT NULL
SELECT #sql = #sql + ' AND (ai.AliasLName LIKE #xLName OR ai.LName LIKE #xLName)'
IF #dtApplicationStart IS NOT NULL
SELECT #sql = #sql + ' AND (CONVERT(char(10), acct.dtApplication, 101) >= #xdtApplicationStart)'
IF #dtApplicationEnd IS NOT NULL
SELECT #sql = #sql + ' AND (CONVERT(char(10), acct.dtApplication, 101) <= #xdtApplicationEnd)'
IF #CompanyName IS NOT NULL
SELECT #sql = #sql + ' AND (ao.CompanyName LIKE #xCompanyName)'
IF #DaysInTask IS NOT NULL
SELECT #sql = #sql + ' AND (DATEDIFF(day, awt.dtEnter, GETDATE()) >= #xDaysInTask)'
IF #AcctNum IS NOT NULL
SELECT #sql = #sql + ' AND (acct.AcctNum LIKE #xAcctNum)'
IF #BranchNums IS NOT NULL
--Can't use a parameter of the executesql for the list of affinity numbers.
SELECT #sql = #sql + ' AND (acct.AcctAffinityNum IN (' + #BranchNums + ') OR luA.AffinityNum IN (' + #BranchNums + '))'
IF #WorkflowID IS NOT NULL
SELECT #sql = #sql + ' AND (w.WorkflowID = #xWorkflowID)'
IF #OriginationID IS NOT NULL
SELECT #sql = #sql + ' AND (a.OriginationID = #xOriginationID)'
IF #QueueID IS NOT NULL
SELECT #sql = #sql + ' AND (t.QueueID = #xQueueID)'
IF #TaskStageIDs IS NOT NULL
--Can't use a parameter of the executesql for the list of affinity numbers.
SELECT #sql = #sql + ' AND (lts.TaskStageID IN (' + #TaskStageIDs + '))'
IF #TaskIDs IS NOT NULL
--Can't use a parameter of the executesql for the list of affinity numbers.
SELECT #sql = #sql + ' AND (t.TaskID IN (' + #TaskIDs + '))'
IF #DaysAged IS NOT NULL
SELECT #sql = #sql + ' AND ISNULL(cteAge.Age + 1, 0) <= #xDaysAged'
--SELECT #sql = #sql + ' AND (DATEDIFF(day, acct.dtApplication, GETDATE()) + 1 = #xDaysAged)'
IF #LastActivityStart IS NOT NULL
SELECT #sql = #sql + ' AND (CONVERT(char(10), awt.dtEnter, 101) >= #xLastActivityStart)'
IF #LastActivityEnd IS NOT NULL
SELECT #sql = #sql + ' AND (CONVERT(char(10), awt.dtEnter, 101) <= #xLastActivityEnd)'
IF #Market IS NOT NULL
SELECT #sql = #sql + ' AND (lam.Market = #xMarket OR acctLam.Market = #xMarket)'
IF #EmailTypeIDs IS NOT NULL
SELECT #sql = #sql + ' AND (note.NoteReasonID IN (' + #EmailTypeIDs + '))'
IF #SOAApplID IS NOT NULL
SELECT #sql = #sql + ' AND asa.SOAApplID = #xSOAApplID UNION
SELECT NULL ApplID, NULL AcctID, sa.dtAdded dtApplication, sap.FName, sap.MName, sap.LName, sap.SSN, sap.Email, NULL CompanyName,NULL DBAName,
NULL TaxID, NULL AcctNum, 145 AcctAffinityNum, ''145'' AffinityNum, luA.AffinityName, NULL TaskDesc, NULL dtEnter,
NULL DaysInTask, NULL QueueDesc, NULL WorkflowID, ''SEI Online App'' WorkflowDesc,NULL OriginationID, NULL OriginationDesc, NULL dtCheckOut,
NULL UserCheckOut, NULL GUIDCheckout, NULL TaskStageDesc,
0, DATEDIFF(day, sa.dtAdded, GETDATE()) + 1 DaysAged, sa.SOAApplID,'' '', '' '', '' '' dtEnter, '' ''DecisionType,'' '' Market,
'' ''Request,'' ''SourceAccountTypeDescription,'' ''FundingStatus,'' ''BrokerCode, '' ''TIN,'' ''BusPurpose,'' ''Note,'' ''t,
'' ''t1,'' '' RelationshipCode, '' '' RelationshipCodeDesc FROM SOAApplication sa LEFT JOIN AccountSOAApplication asa
ON sa.SOAApplID = asa.SOAApplID JOIN SOAApplicant sap ON sa.SOAApplID = sap.SOAApplID JOIN luAffinity luA ON luA.AffinityNum = ''145''
WHERE asa.SOAApplID IS NULL AND sa.SOAApplID = #xSOAApplID AND sap.PrimaryContact = 1'
IF #debug = 1
PRINT #sql
IF #debug = 1
PRINT #sql
SELECT #paramlist =
'#xSSN char(9),
#xFName varchar(25),
#xLName varchar(30),
#xdtApplicationStart datetime,
#xdtApplicationEnd datetime,
#xCompanyName varchar(50),
#xDaysInTask int,
#xAcctNum varchar(11),
#xWorkflowID int,
#xOriginationID tinyint,
#xQueueID int,
#xDaysAged int,
#xMarket varchar(50),
#xSOAApplID int,
#xLastActivityStart datetime,
#xLastActivityEnd datetime'
IF #Debug = 1 PRINT LEN(#SQL)
EXEC sp_executesql #sql, #paramlist,
#SSN,
#FName,
#LName,
#dtApplicationStart,
#dtApplicationEnd,
#CompanyName,
#DaysInTask,
#AcctNum,
#WorkflowID,
#OriginationID,
#QueueID,
#DaysAged,
#Market,
#SOAApplID,
#LastActivityStart,
#LastActivityEnd
So when you add EXECUTE AS SELF to a procedure, it's the same as saying "Execute this procedure as though the person who created it is running it". So whoever deploys the procedure (under whatever principal account) is the one that will be the basis for what the procedure uses.
I'm presuming that your deployment strategy is to have an administrator run the CREATE/ALTER steps using the sa account. Your DBAs are probably following best practice and not having the sa account own the databases on the server (and possibly not have read access at all), so you get the security error.
Given all that, in your current situation, you're probably not going to use EXECUTE AS SELF, or at least I suspect so. In terms of when you would want to use it in a more general sense, it's hard to give a blanket answer. Short version is if you have a situation where you ("you" being a principal you can log in as) need to run an object at your level of permissions rather than whatever permissions the caller has.