Stored Procedure errors out only when calling from a trigger - sql-server

I am using SQL Server to programming something that's triggered by a UPDATE even in a table.
So the structure is like: in the trigger, I have:
EXEC StoredProcedure1
And in StoredProcedure1 I have:
INSERT dbo.UnbalancedFreqStops
SELECT APremise AS PremiseID
,geography::ConvexHullAggregate(Location) AS Shape
FROM
(SELECT
A.[Premise ID] AS APremise, B.[Premise ID] AS BPremise,
B.LatLon AS Location, B.[Service Frequency] AS FreqT, B.Mon_Routed AS MonT,
B.Tue_Routed AS TueT, B.Wed_Routed AS WedT, B.Thu_Routed AS ThuT,
B.Fri_Routed AS FriT, B.Sat_Routed AS SatT, B.Sun_Routed AS SunT
FROM
dbo.Weekly AS A
INNER JOIN
dbo.Weekly AS B ON A.LatLon.STDistance(B.LatLon) <= (80 * 2)
) AS Clusters
GROUP BY
APremise
HAVING
MAX(FreqT) <> (MAX(MonT) + MAX(TueT) + MAX(WedT) + MAX(ThuT) + MAX(FriT) + MAX(SatT) + MAX(SunT));
It's interesting that it errors out with violation of primary key error (PremiseId being unique PK) ONLY WHEN I am calling the stored procedure from the trigger. And the stored procedure runs fine if I (1) run it alone, or (2) call it from another stored procedure.
Moreover, I ran the query alone, and found there is NO duplicate key AT ALL.
Can somebody enlighten me?
Thanks!

Related

SQL Server execution speed varies wildly depending on how parameters are provided to an inline table function

I am investigating a problem with the execution speed of an inline table function in SQL Server. Or that's where I thought the problem lay. I came across
T-SQL code is extremely slow when saved as an Inline Table-valued Function
which looked promising, since it described what I was seeing, but I seemed to have the opposite problem - when I passed variables to my function, it took 17 seconds, but when I ran the code of my function in a query window, using DECLARE statements for the variables (which I thought effectively made them literals), it ran in milliseconds. Same code, same parameters - just wrapping them up in an inline table function seemed to drag it way down.
I tried to reduce my query to the minimum possible code that still exhibited the behaviour. I am using numerous existing inline table functions (all of which have worked fine for years), and managed to strip my code down to needing just a call of one existing inline table function to be able to highlight the speed difference. But in doing so I noticed something very odd
SELECT strStudentNumber
FROM dbo.udfNominalSnapshot('2019', 'REG')
takes 17 seconds whereas
DECLARE #strAcademicSessionStart varchar(4) = '2019'
DECLARE #strProgressCode varchar(12)= 'REG'
SELECT strStudentNumber
FROM dbo.udfNominalSnapshot(#strAcademicSessionStart, #strProgressCode)
takes milliseconds! So nothing to do with wrapping the code in an inline table function, but everything to do with how the parameters are passed to a nested function within it. Based on the cited article I'm guessing there are two different execution plans in play, but I have no idea why/how, and more importantly, what I can do to persuade SQL Server to use the efficient one?
P.S. here is the code of the inner UDF call in response to a comment request
ALTER FUNCTION [dbo].[udfNominalSnapshot]
(
#strAcademicSessionStart varchar(4)='%',
#strProgressCode varchar(10)='%'
)
RETURNS TABLE
AS
RETURN
(
SELECT TOP 100 PERCENT S.strStudentNumber, S.strSurname, S.strForenames, S.strTitle, S.strPreviousSurname, S.dtmDoB, S.strGender, S.strMaritalStatus,
S.strResidencyCode, S.strNationalityCode, S.strHESAnumber, S.strSLCnumber, S.strPreviousSchoolName, S.strPreviousSchoolCode,
S.strPreviousSchoolType,
COLLEGE_EMAIL.strEmailAddress AS strEmailAlias,
PERSONAL_EMAIL.strEmailAddress AS strPersonalEmail,
P.[str(Sub)Plan], P.intYearOfCourse, P.strProgressCode,
P.strAcademicSessionStart, strC2Knumber AS C2K_ID, AcadPlan, strC2KmailAlias
,ISNULL([strC2KmailAlias], [strC2Knumber]) + '#c2kni.net' AS strC2KmailAddress
FROM dbo.tblStudents AS S
LEFT JOIN
dbo.udfMostRecentEmail('COLLEGE') AS COLLEGE_EMAIL ON S.strStudentNumber = COLLEGE_EMAIL.strStudentNumber
LEFT JOIN
dbo.udfMostRecentEmail('PERSONAL') AS PERSONAL_EMAIL ON S.strStudentNumber = PERSONAL_EMAIL.strStudentNumber
INNER JOIN
dbo.udfProgressHistory(#strAcademicSessionStart) AS P ON S.strStudentNumber = P.strStudentNumber
WHERE (P.strProgressCode LIKE #strProgressCode OR (SUBSTRING(#strProgressCode, 1, 1) = '^' AND P.strProgressCode NOT LIKE SUBSTRING(#strProgressCode, 2, LEN(#strProgressCode)))) AND
(P.strStudentNumber NOT IN
(SELECT strStudentNumber
FROM dbo.tblPilgrims
WHERE (strAcademicSessionStart = #strAcademicSessionStart) AND (strScheme = 'BEI')))
ORDER BY P.[str(Sub)Plan], P.intYearOfCourse, S.strSurname
)
Expanding on #Ross Pressers comment, this might not really be an answer, but demonstrates what is happening (a bit), with my understanding (which could be wrong!) of what is happening...
Run the setup code at the end and then....
Execute the following with query plan on (Ctrl-M)... (note: depending on the random number generator you may or may not get any results, that does not affect the plan)
declare #one varchar(100) = '379', #two varchar(200) = '726'
select * from wibble(#one, #two) -- 1
select * from wibble('379', '726') -- 2
select * from wibble(#one, #two) OPTION (RECOMPILE) -- 3
select * from wibble(#one, #two) -- 4
Caveat. The following is what happens on MY system, your mileage may vary...
-- 1 (and -- 4) are the most expensive.
SQL Server creates a generic plan as it does not know what the parameters are (yes they are defined, but the plan is for wibble(#one, #two) where, at that point, the parameter values are "unknown")
https://www.brentozar.com/pastetheplan/?id=rJtIRwx_r
-- 2 has a different plan
Here, sql server knows what the parameters are, so can create a specific plan, which is quite different to --1
https://www.brentozar.com/pastetheplan/?id=rJa9APldS
-- 3 has the same plan as --2
Testing this further, adding OPTION (RECOMPILE) gets SQL Server to create a specific plan for the specific execution of wibble(#one, #two) so we get the same plan as --2
--4 is there for completeness to show that after all that mucking about the generic plan is still in place
So, in this simple example we have a parameterised TVF being called with identical values, that are passed either as parameters or inline, producing different execution plans and different execution times as per the OP
Set up
use tempdb
GO
drop table if EXISTS Orders
GO
create table Orders (
OrderID int primary key,
UserName varchar(50),
PhoneNumber1 varchar(50),
)
-- generate 300000 with randon "phone" numbers
;WITH TallyTable AS (
SELECT TOP 300000 ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS [N]
FROM dbo.syscolumns tb1,dbo.syscolumns tb2
)
insert into Orders
select n, 'user' + cast(n as varchar(10)), cast(CRYPT_GEN_RANDOM(3) as int)
FROM TallyTable;
GO
drop function if exists wibble
GO
create or alter function wibble (
#one varchar(4) = '%'
, #two varchar(4) = '%'
)
returns table
as
return select * from Orders
where PhoneNumber1 like '%' + #one + '%'
and PhoneNumber1 like '%' + #two + '%'
or (SUBSTRING(#one, 1, 1) = '^' AND PhoneNumber1 NOT LIKE SUBSTRING(#two, 2, LEN(#two)))
and (select 1) = 1
GO
Problem was overcome (I wouldn't say "fixed") by following up on Ross Presser's observation about the complexity of udfProgressHistory. This sucked data from a table tblProgressHistory which was joined to itself. The table is added to annually. I think this year's additional 2K records must have caused the sudden cost-hike when using a particular execution plan. I deleted >2K redundant records and we're back to sub-second execution.

what is the error? (SELECT [Data] FROM Split(#ProductName,','))

The stored procedure that used work with multiple parameters but it stops working.
I am trying to fix the stored procedure that used to work but suddenly create an error 'Invalid object name 'Split''. This is the procedure that someone else wrote so I am not exactly sure what 'Split' is. Is this some sort of command or what?
This is the stored Procedure that used to work but not anymore.
DECLARE #ProductName NVARCHAR(MAX) = '9x95dk36-2727-9401-8948-161740000000,150t3vh6-1230-4449-8846-173120000000'
SELECT
m.[member_id]
, m.external_member_id
, m.last_name
, m.first_name
, m.middle_name
, e.effective_date
,[termination_date]
, REPLACE(bhp.name_full_path,'CW > Medicaid > WI > SSI > ','') AS BHP
, pr.product_name
,pr.product_ID
INTO #ActiveSSIMembers
FROM
[Eligibility] as e
INNER JOIN Product as pr on e.product_id = pr.product_id
INNER JOIN Member as m on e.member_id = m.member_id
INNER JOIN BhpNode as bhp on m.bhp_node_id = bhp.bhp_node_id
WHERE
pr.product_ID IN (SELECT [Data] FROM Split(#ProductName,','))
We need to use multiple parameters for the query.
From the code you have posted, it seems Split is a Table-Valued User-Defined function that takes NVarchar parameter(seperated by ',') and returns rows of split values under the column name Data.
You are missing that user-defined function in your database where this query is being executed. Either this has been removed or you running the query in a different database.
Try navigating to Table-Valued Functions as below and make sure you have a function called Split in there(instead of 'TestFunction' in that image). If not, you can create your our function to split the values and add it to your database.
You can take help from this thread to create one

How to determine who performed DROP/DELETE on Sql Server database objects?

There is always a need to find out details, either intentionally Or mistakenly someone executed DROP/DELETE command on any of following SQL Server database objects.
DROPPED - Table from your database
DROPPED - Stored Procedure from your database
DELETED - Rows from your database table
Q. Is there TSQL available to find db user who performed DELETE/DROP?
Q. What kind of permissions are needed for user to find out these details?
Did you check this ?
Right click on database.
Go to as shown in image :
Solution 2 :
This query gives alot of useful information for a database(apply filter as required) :
DECLARE #filename VARCHAR(255)
SELECT #FileName = SUBSTRING(path, 0, LEN(path)-CHARINDEX('\', REVERSE(path))+1) + '\Log.trc'
FROM sys.traces
WHERE is_default = 1;
SELECT gt.HostName,
gt.ApplicationName,
gt.NTUserName,
gt.NTDomainName,
gt.LoginName,
--gt.SPID,
-- gt.EventClass,
te.Name AS EventName,
--gt.EventSubClass,
-- gt.TEXTData,
gt.StartTime,
gt.EndTime,
gt.ObjectName,
gt.DatabaseName,
gt.FileName,
gt.IsSystem
FROM [fn_trace_gettable](#filename, DEFAULT) gt
JOIN sys.trace_events te ON gt.EventClass = te.trace_event_id
WHERE EventClass in (164) --AND gt.EventSubClass = 2
ORDER BY StartTime DESC;

SQL Server FOR/AFTER trigger

I have an issue with an assignment. I believe I have the code all worked out properly but I keep getting a syntax error saying that the column "Total" Does not exist. I was under the impression that when you used "AS" it renamed the column that you are trying to use.
Here is my code any pointers would be greatly appreciated.
Use [IST278EagleCorp13-1]
Go
Alter Trigger DPInvOrderTrigger
On InventoryPart
For insert
As
If exists ( Select Count(ReorderLevel * 4) ReorderLevel,Count(StockOnOrder + StockLevel) AS Total
From InventoryPart
Where Total > ReorderLevel)
Begin
RaisError('Inventory to low. Transaction failed.',16,1)
rollback tran
End
These are the directions for this assignment.
/* Create a FOR|AFTER trigger named xxInvOrderTrigger for updates
to the InventoryPart table. If an update produces a record where
the (stockOnOrder + stockLevel) > (4 * reorderLevel) raise an
error (display an error) and rollback the change. */
To my understanding you are using SQL Server as your RDBMS and if I am not wrong in your below query Total is a column alias and you can't use column alias in where clause. That's why the error is for.
See a sample fiddle here for your understanding http://sqlfiddle.com/#!3/f902c/1
Select Count(ReorderLevel * 4) ReorderLevel,
Count(StockOnOrder + StockLevel) AS Total
Rather you can do it using derived table like below
select ReorderLevel,
Total
from
(
Select Count(ReorderLevel * 4) ReorderLevel,
Count(StockOnOrder + StockLevel) AS Total,
ReorderLevel
From InventoryPart
) tab
Where Total > ReorderLevel

Retrieving data from a MS SQL 2012 table based on FK value from another table using stored procedure

I am working on MS SQL Server 2012. I have two tables - Associates and Clients and they have M:N relation so I have another table MapClientToAssociates where I have two foreign keys - ClientID and AssociateID. What I want to achieve is by providing a ClientID to take all the AssociateID's for this Client and then take all the information about each Associate (As I wrote, the relation is M:N so there can be several Associates for a certain client) and I want to return this data.
So basically I want to return rows containing :
`ID` - from `MapClientToAssociates`
`ClientID` - from `MapClientToAssociates`
`AssociateID` - from `MapClientToAssociates`
[column1] - from `Associates` (based on the `AssociateID` value)
[column2] - from `Associates` (based on the `AssociateID` value)
.
.
.
[columnN] - from `Associates` (based on the `AssociateID` value)
I tried to follow an existing code that is doing something pretty similar to that :
CREATE PROCEDURE [dbo].[usp_ClientGetAssociates]
#ClientID int
AS
BEGIN
If Exists (Select * From dbo.MapClientToAssociates map Where map.ClientID = #ClientID)
Begin
Declare #AssociateID int = (Select * map.AssociateID From dbo.MapClientToAssociates map Where map.ClientID = #ClientID)
And I get an error that I don't understand at the very beginning - Declare #AssociateID int = (Select * map.AssociateID - here map.AssociateID map is underscored in red saying Incorrect syntax near map) but I have to admit I don't have any experience with T-SQL or writing stored procedures and this seems like a standard stuff for a sproc to do so I would appreciate any help to make this sproc working and hopefully later I'll have the time to examine how exactly the code is working, but for now the most important thing for me is to make the sproc returns the result I want.
This clause (Select * map.AssociateID From dbo.MapClientToAssociates map Where map.ClientID = #ClientID) is returning a derived table of integer values. You are trying to assign it to a scalar (single) integer value, which does not make sense.
As for the actual syntax error, this :
Select * map.AssociateID From dbo.MapClientToAssociates map Where map.ClientID = #ClientID
is invalid because you would need to either remove the * or put a comma between it and the map.AssociateID.
This is how I would write this myself:
CREATE PROCEDURE [dbo].[usp_ClientGetAssociates]
#ClientID int
AS
BEGIN
Select act.*
From dbo.MapClientToAssociates map
Left Join dbo.Associates as act ON act.AssociateID = map.AssociateID
Where map.ClientID = #ClientID)
End
Unless I needed to consume the returned rowset in another SQL procedure or expression, then I would write it as a table-valued function instead.
CREATE PROCEDURE [dbo].[usp_ClientGetAssociates]
#ClientID int
AS
BEGIN
Select map.*, ass.*
from dbo.MapClientToAssociates map, dbo.Associates ass
where ass.AssociateID = map.AssociateID
and map.ClientID = #ClientID
If this response is wrong, can you provide a script for create and populate table and the full code of stored procedure?

Resources