SQL Job Failing but not the stored procedure - sql

EDIT 4/18:
I want to thank everyone who has answered so far. As a test I have set up a new job which has just one step in it,
EXECUTE p_CallLog_GetAbandonedCallsForCallList
This procedure itself runs just fine and reports no errors or warnings but will not run when executed as part of a job. The error I receive when running the job is:
Executed as user: NT AUTHORITY\SYSTEM. OLE DB provider 'SQLOLEDB' reported an error. [SQLSTATE 42000] (Error 7399) [SQLSTATE 01000] (Error 7312) OLE DB error trace
[OLE/DB Provider 'SQLOLEDB' IDBInitialize::Initialize returned 0x80004005: ].
[SQLSTATE 01000] (Error 7300). The step failed.
I have tried changing the run as user selection and every other selection I try results in an error of:
Executed as user: Db2WebCal. Remote access not allowed for Windows NT user activated
by SETUSER. [SQLSTATE 42000] (Error 7410). The step failed.
All of the users I have tried do have a local login setup on the linked server.
The p_CallLog_GetAbandonedCallsForCallList procedure is as follows:
CREATE PROCEDURE [dbo].[p_CallLog_GetAbandonedCallsForCallList]
AS
BEGIN
DECLARE #SrvrName varchar(255)
DECLARE #HoursOld int --only get abandoned call that are fresher than #HoursOld
SET #HoursOld = 2 /*was normal default */
SET #SrvrName = CAST(ServerProperty('MachineName') as varchar(255))
CREATE TABLE #tmpAbandonedCalls
(
[ID] INT NULL,
StartTime DateTime NULL,
CallerIDNumber varchar(255) NULL,
CallerIDCount INT NULL,
Holdtime INT NULL,
DIDNumber varchar(20) NULL,
CustomData varchar(255) NULL,
FromFirstName varchar(100) NULL,
FromLastName varchar(100) NULL,
CallType int NULL
)
IF #SrvrName <> 'ROME' BEGIN
INSERT INTO #tmpAbandonedCalls
SELECT
cl.[ID],
cl.StartTime,
cl.CallerIDNumber,
LastAbandonedCallID.cnt as CallerIDCount,
cl.HoldTime,
right(cl.DIDNumber,10) as DIDNumber,
REPLACE(right(left(cl.CustomData,charindex(';',cl.CustomData) - 1), len(left(cl.CustomData,charindex(';',cl.CustomData) - 1)) - charindex('=',cl.CustomData)) , ' NAME','') as CustomData,
cl.FromFirstName,
cl.FromLastName,
2 AS CallType -- T_L_CallType obctAbandoned
FROM
[StrataCS.Perceptionist.local].TVDB.dbo.CallLog CL LEFT OUTER JOIN
/*=============================================
This derived table lists the CallerID's and the most
recent Call Log ID for candidate calls
=============================================*/
(
SELECT
CallerIDNumber, Max(ID) as ID, count(*) as cnt
FROM
[StrataCS.Perceptionist.local].TVDB.dbo.CallLog CL
WHERE
--Last n days
--StartTime >= DATEADD(dd,-#DaysBack,CAST(CONVERT(VARCHAR(10),GETDATE(),112) as DATETIME))
--Get calls only from within the last two hours.
StartTime >= DATEADD(hh,-2,GETDATE())
AND
LEFT(CustomData,11) = 'CompanyName'
AND
CHARINDEX('Db2ID', CustomData) > 0
AND
CallerIDNumber <> ''
AND
Len(CallerIDNumber) = 10
AND
(cl.HoldTime > 0) --0 holdtime is generally an automated call that we will not want to call again
GROUP BY
CallerIDNumber
) as LastAbandonedCallID
ON
CL.CallerIDNumber = LastAbandonedCallID.CallerIDNumber
WHERE
--Last n days
--StartTime >= DATEADD(dd,-#DaysBack,CAST(CONVERT(VARCHAR(10),GETDATE(),112) as DATETIME))
--Get calls only from within the last two hours.
cl.StartTime >= DATEADD(hh,(-1 * #HoursOld),GETDATE())
AND
--determine abandoned calls
CASE
WHEN CL.Result IN (0, 3, 11) THEN 0
WHEN CL.Result IN (1, 2) THEN 1
WHEN CL.Result IN (4, 9) THEN 2
WHEN CL.Result = 5 THEN 3
WHEN CL.Result = 6 THEN 4
WHEN CL.Result = 8 THEN 5
WHEN CL.Result = 10 THEN 6
WHEN CL.Result = 12 THEN 7
WHEN CL.Result = 13 THEN 8
WHEN CL.Result = 14 THEN 9
ELSE -CL.Result
END = 0
--Calls which have hit the call queue will have both a CompanyName and Db2ID in custom data.
AND
LEFT(CustomData,11) = 'CompanyName'
AND
CHARINDEX('Db2ID', CustomData) > 0
AND
--omit calls with no caller id -- or from IGC 6143847400
(
CL.CallerIDNumber <> ''
--OR CL.CallerIDNumber = '6143847400'
)
AND
--make sure the caller id has 10 digits
Len(CL.CallerIDNumber) = 10
AND
--The abandoned call must be the most recent call from this caller id
--CL.ID >= isnull(LastAbandonedCallID.ID,-#DaysBack)
CL.ID >= isnull(LastAbandonedCallID.ID,-1)
AND
(CL.HoldTime > 0) --0 holdtime is generally an automated call that we will not want to call again
ORDER BY
--sort by call time, most recent first.
StartTime DESC
-- Company has opted out of the Abandoned Callback program
DELETE #tmpAbandonedCalls
FROM
#tmpAbandonedCalls tmp
INNER JOIN dbo.T_CompanyPhoneSetup cps
on tmp.DIDNumber = cps.DID
INNER JOIN T_CompanyAbandonedCallbackOptOut aco
ON cps.CompanyID = aco.CompanyID
AND
aco.OptOutIsActive = 1
--Delete calls that have had a terminating outcome or have been returned within the last 20 minutes
DELETE #tmpAbandonedCalls
FROM
#tmpAbandonedCalls
INNER JOIN
(
SELECT
c.CallLogID
FROM
T_Call c (nolock)
INNER JOIN #tmpAbandonedCalls tmp
on tmp.ID = c.CallLogID
LEFT OUTER JOIN T_L_Need n
ON c.NeedID = n.NeedID
LEFT OUTER JOIN T_L_Outcome o
ON c.OutcomeID = o.OutcomeID
LEFT OUTER JOIN dbo.T_L_CallCampaignDetailStatus ccds
ON o.CCDetailStatusID = ccds.CCDetailStatusID
LEFT OUTER JOIN dbo.T_Company co
ON c.CompanyID = co.CompanyID
LEFT OUTER JOIN dbo.T_L_ProductLine pl
ON co.ProductLineID = pl.ProductLineID
LEFT OUTER JOIN T_CompanyAbandonedCallbackOptOut aco
ON (c.CompanyID = aco.CompanyID) and (aco.OptOutIsActive = 1)
GROUP BY
c.CallLogID
HAVING
--Calls that have an outcome that include at least one terminating outcome
(SUM(CAST(isnull(ccds.IsTerminal,0) as INT)) > 0)
OR
(
--Calls that have been returned less than 20 minutes ago
(SUM(CAST(isnull(ccds.IsTerminal,0) as INT)) = 0)
AND
GETDATE() <= DATEADD(mi,20,Max(c.EnteredOn))
)
OR
(
--Calls for Perceptionist Lite product line
(MAX(co.ProductLineID) = 2) -- Perceptionist Lite
)
) LastCall
ON
#tmpAbandonedCalls.[ID] = LastCall.CallLogID
END
INSERT INTO T_OutboundCallList
(TrackingID, Company, CompanyDID, Phone, CallType)
SELECT
#tmpAbandonedCalls.[ID],
#tmpAbandonedCalls.CustomData,
#tmpAbandonedCalls.DIDNumber,
#tmpAbandonedCalls.CallerIDNumber,
#tmpAbandonedCalls.CallType
FROM
#tmpAbandonedCalls
ORDER BY
StartTime
END
GO
ORIGINAL:
I have the following stored procedure that is used to fill a table with values.
PROCEDURE [dbo].[p_OutboundCallList_Create]
AS
BEGIN
TRUNCATE TABLE T_OutboundCallList
EXECUTE p_LeadVendor_GetCallsForCallList
EXECUTE p_CallCampaign_GetCallsForCallList
EXECUTE p_CallLog_GetAbandonedCallsForCallList
EXECUTE p_NoSaleFollowUp_GetCallsForCallList
END
Running this works fine and the table is filled. After creating a job and adding the following step:
EXEC p_OutboundCallList_Create
The job fails with the following error message:
Executed as user: NT AUTHORITY\SYSTEM. Warning: Null value is eliminated
by an aggregate or other SET operation. [SQLSTATE 01003] (Message 8153)
Warning: Null value is eliminated by an aggregate or other SET operation.
[SQLSTATE 01003] (Message 8153) OLE DB provider 'SQLOLEDB' reported an error.
[SQLSTATE 42000] (Error 7399) [SQLSTATE 01000] (Error 7312) OLE DB error trace
[OLE/DB Provider 'SQLOLEDB' IDBInitialize::Initialize returned 0x80004005: ].
[SQLSTATE 01000] (Error 7300). The step failed.
If I comment out the line
EXECUTE p_CallLog_GetAbandonedCallsForCallList
..the job runs fine. This stored procedure (p_CallLog_GetAbandonedCallsForCallList) does rely on a linked server and runs fine by itself and also runs fine when I run p_OutboundCallList_Create. It only fails when I run it as part of a job. I have tried running as a different user (sa, benderle, etc.) and always get the same result (failed).

"Null value is eliminated by an aggregate or other SET operation" is a SQL Server warning, which means you won't see it in the output if you run your query and this warning is raised (switch to the "Messages" tab in SQL Server Management Studio to see this).
Although it's a warning, presumably any warnings in a SQL job cause the job to error out. Fix the p_CallLog_GetAbandonedCallsForCallList procedure so it doesn't raise that warning and you job will work as expected.

I woulf be interested in seeing the code in p_CallLog_GetAbandonedCallsForCallList, as it may explain more as to why this is happening for the user NT AUTHORITY\SYSTEM.
The message occurs when you perform an aggregation (e.g. sum(), max(), count() on a data set that has a null in it).
To fix this, you may need to put an ISNULL() around the field in question, or use an INNER JOIN instead of a LEFT or RIGHT JOIN.

To disable warning that throw error in Sql Server Agent tasks.
The tasks that are launched from the SQL SERVER AGENT (scheduled), give an error, if there is a warning of the style:
"Null value is eliminated by an aggregate or other SET operation"
This message can be disabled by SET ANSI_WARNING OFF
But in some cases, there are sql statements that require this value to be on to avoid errors like:
Heterogeneous queries require the ANSI_NULLS and ANSI_WARNINGS options to be set for the connection. This ensures consistent query semantics. Enable these options and then reissue your query
Therefore, there is no other solution than to prevent SQL SERVER AGENT from considering it an error.
This can be achieved by modifying the values ​​in the REGISTRY (REGEDIT)
Modify the entries, depending on your version of SQL SERVER:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL11.MSSQLSERVER\SQLServerAgent
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL11.SQL2012\SQLServerAgent
Add as 'no error' the message id you want to disable: 7405

Related

Excel "The multi-part identifier could not be bound" When Using Parameters

I have a SQL query in Excel that will work just fine if I hard code the dates into the query. As soon as I try to change them to ?'s it gives the error. I've used parameterized queries like this in loads of reports, so I'm not sure why this one is suddenly not working.
The full error is [Microsoft][ODBC SQL Server Driver][SQL Server]The multi-part identifier "cancel.arrival_date" could not be bound. which pops up twice.
Here is my query with the ? in it that gives the error:
SELECT cancel.reservation_number, (client.last_name + ', ' + client.first_name) AS 'guest_name',
cancel.cancel_date_time, cancel.arrival_date,
DATEDIFF(DAY, cancel.cancel_date_time, cancel.arrival_date) AS 'Days Out', cancel.cancel_reason,
CASE
WHEN EXISTS (SELECT *
FROM gbfol_head head
LEFT JOIN gbfol_det det ON head.folio_number = det.folio_number
WHERE cancel.reservation_number = head.source_id
AND head.folio_type <> 'b' AND det.posting_code = 'admn') THEN
'ADMN Charged'
ELSE
'No ADMN Fee'
END AS 'ADMN',
cancel.amount, cancel.cancel_clerk_code, cancel.sba_text
FROM canceled cancel
LEFT JOIN reservation res ON cancel.reservation_number = res.reservation_number
LEFT JOIN clients client ON res.home_client_code = client.client_code
WHERE DATEDIFF(DAY, cancel.cancel_date_time, cancel.arrival_date) < 21
AND (cancel.arrival_date BETWEEN ? AND ?)
If I change the last line to AND (cancel.arrival_date BETWEEN '2019-12-01' AND '2019-12-10') it works fine.
I have also tried using AND (cancel.arrival_date >= ? AND cancel.arrival_date <= ?) which didn't work either, same error.

How to run procedure without parameter in Teradata

How to run procedure without parameter in Teradata
I'm trying with : call db1.proc_dbOSA()
Error Msg:
Call failed 3707: PROC_DBOSA: Syntax error, expected something
like a name or a Unicode delimited identifier between ‘(‘ and ‘)’
New Procedure with error result.
When i run only code then everything works ok.
REPLACE PROCEDURE db1.proc_dbOSA()
BEGIN
DELETE FROM db1.LOG_dbOSA;
INSERT INTO
db1.LOG_dbOSA
(StoreNo, IDX, Flow, Status, MRP, OSA_IDX, OSA_AC)
WITH a AS (
SELECT
c.StoreCode,
CAST(SUBSTRING(c.ArticleCode FROM 13 FOR 6) AS INT) AS IDX,
RpType,
CASE
WHEN c.MinimumTargetStockWrpl >= l.MinimumTargetStockWrpl THEN CAST(l.MinimumTargetStockWrpl AS INT)
WHEN c.MinimumTargetStockWrpl < l.MinimumTargetStockWrpl THEN CAST(c.MinimumTargetStockWrpl AS INT)
End AS StoreMin,
c.ValUnrestrictedStock
FROM
db1.tab1 c
INNER JOIN
(
SELECT
StoreCode,
ArticleCode,
MinimumTargetStockWrpl
FROM
db1.tab1
WHERE
ProcessingDate = CURRENT_DATE - 14
) l ON c.StoreCode = l.StoreCode AND c.ArticleCode = l.ArticleCode
WHERE
c.ProcessingDate = CURRENT_DATE AND c.MinimumTargetStockWrpl IS NOT NULL AND l.MinimumTargetStockWrpl IS NOT NULL AND l.MinimumTargetStockWrpl > 0
)
, t AS
(
SELECT
CAST(SUBSTRING(ArticleCode FROM 13 FOR 6) AS INT) AS IDX,
RpType,
ArticlesPlanner
FROM
DWH_db_V.STK_B_ARTICLE_DAY_V
WHERE
ProcessingDate = CURRENT_DATE AND StoreCode = 'DR04'
)
SELECT
a.StoreCode,
a.IDX,
t.RpType,
t.ArticlesPlanner,
a.RpType,
CASE
WHEN a.ValUnrestrictedStock > 0 THEN 1
WHEN a.ValUnrestrictedStock <= 0 THEN 0
End AS OSA_IDX,
CASE
WHEN a.ValUnrestrictedStock >= StoreMin THEN 1
WHEN a.ValUnrestrictedStock < StoreMin THEN 0
End AS OSA_AC
FROM
a
LEFT JOIN
t ON t.IDX = a.IDX;
End;
BTEQ Error:
+---------+---------+---------+---------+---------+---------+---------+----
Call proc_dbOSA;
Call proc_dbOSA;
$
* Failure 3707 Syntax error, expected something like '(' between the word
'proc_dbOSA' and ';'.
Statement# 1, Info =18
* Total elapsed time was 1 second.
Call proc_dbOSA();
* Failure 3707 PROC_DBOSA:Syntax error, expected something like a name or
a Unicode delimited identifier between '(' and ')'.
* Total elapsed time was 1 second.
Stored procedures do not support the following:
EXPLAIN and USING request modifiers within a stored procedure
EXECUTE macro statement
WITH clause within a stored procedure.
Stored procedures, as well as macros, do not support the following query logging statements:
BEGIN QUERY LOGGING
END QUERY LOGGING
FLUSH QUERY LOGGING
REPLACE QUERY LOGGING

SELECT with CASE after UPDATE uses old value

I have a problem with a combination of sql statements generated by entity-framework.
It looks like the updated value of the powerloss field is not immediately set after the update statement completes and the select gets executed.
I don't know if that's even possible.
Maybe I'm just missing something.
The updated and selected rows and the data in the table after the code executes are correct.
What it should do (and it does it 99% of the time)
I get a counterValue from a device and insert it into a table on a sql-server 2008 R2 (SP3). If the device has lost power and at some point is back, the field "powerloss" in the last counterValue entry in the database will be updated to 1(true). By default, the field is 0(false).
After that, I query the last counterValue of this device and negate it.
But only if the field "powerloss" is 0(false). Otherwise the query must return zero.
What goes wrong
Sometimes (very rare) I get the negated counterValue when the powerloss field was updated to 1(true) right before the select...
That's at least what my log-file shows me (every query is logged).
What the code does
Create dbContext
BeginTransaction(isolationLevel.ReadComitted)
WriteNewCounterValue (after Powerloss)
Update field powerloss=true
Select counterValue depend on value in powerloss field
offset = (From qItem In DB.SlaveCounterEntries
Where qItem.deviceId= deviceId
And qItem.Received < timestamp
Order By qItem.Received Descending
Select If(qItem.Powerloss = True, 0, -qItem.CounterValue)
Take 1).SingleOrDefault()
Insert new counterValue in Table
Commit Transaction
Dispose dbContext
The gernerated sql statements
The update statement:
UPDATE [dbo].[slaveCounter]
SET [powerloss] = #0
WHERE ([id] = #1)
-- #0: 'True' (Type = Boolean)
-- #1: '3371747' (Type = Int32)
-- Executing at 29.06.2018 05:57:24 +02:00
-- Completed in 0 ms with result: 1
The select statement (14 ms after the update):
SELECT TOP (1)
[Project1].[C1] AS [C1]
FROM ( SELECT
CASE WHEN (1 = [Extent1].[powerloss]) THEN 0 ELSE -([Extent1].[counterValue]) END AS [C1],
[Extent1].[datReceived] AS [datReceived]
FROM [dbo].[slaveCounter] AS [Extent1]
WHERE ([Extent1].[slaveId] = #p__linq__0) AND ([Extent1].[datReceived] < #p__linq__1)
) AS [Project1]
ORDER BY [Project1].[datReceived] DESC
-- p__linq__0: '48' (Type = Int16, IsNullable = false)
-- p__linq__1: '28.06.2018 23:00:03' (Type = DateTime2, IsNullable = false)
-- Executing at 29.06.2018 05:57:24 +02:00
-- Completed in 0 ms with result: SqlDataReader
I found the reason why it seems that the update statement does not work:
An other transaction added a second record which had the same counterValue and was not updated and later be deleted.
So only the "correct" entry remains.
In retrospect, everything seems so clear ^^

Distributed Transaction SQL Error using Linked Server

I'm having some database troubles, and can't seem to find a solution anywhere for this specific problem. I'm trying to grab information from a database using a table on the database and comparing it to a table on a linked server
[3/7/14 10:10:14:181 EST] 00000021 SystemErr R org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: com.microsoft.sqlserver.jdbc.SQLServerException: The operation could not be performed because OLE DB provider "SQLNCLI" for linked server "EADWH02" was unable to begin a distributed transaction.
### The error may involve com.moog.app.weldlog.dao.mybatis.WeldLogMapping.listEmployee-Inline
### The error occurred while setting parameters
### Cause: com.microsoft.sqlserver.jdbc.SQLServerException: The operation could not be performed because OLE DB provider "SQLNCLI" for linked server "EADWH02" was unable to begin a distributed transaction.
Here is one of the specific stored procedures that is throwing this error:
#workOrder varchar(25) = null,
#idPartNumber varchar(25) = null
begin
IF #workOrder is null
SELECT DISTINCT TOP 25 WO.WO_NBR, PARTS.PART_NBR
FROM EADWH02.MEDW.LBR.WO WO
JOIN EADWH02.MEDW.MFG.PARTS PARTS
ON PARTS.PART_KEY = WO.PART_KEY
AND PARTS.SRC_DB_KEY = WO.SRC_DB_KEY
WHERE (WO.WO_TYPE_KEY = '2' or WO.WO_TYPE_KEY = '3' or WO.WO_TYPE_KEY = '4' or WO.WO_TYPE_KEY = '5') and
(PARTS.PART_NBR like '' + #idPartNumber + '%')
ELSE IF #idPartNumber is null
SELECT DISTINCT TOP 25 WO.WO_NBR, PARTS.PART_NBR, dbo.getDescriptions(WO.WO_NBR) as strDescriptions
FROM EADWH02.MEDW.LBR.WO WO
JOIN EADWH02.MEDW.MFG.PARTS PARTS
ON PARTS.PART_KEY = WO.PART_KEY
AND PARTS.SRC_DB_KEY = WO.SRC_DB_KEY
WHERE ((WO.WO_TYPE_KEY = '2' or WO.WO_TYPE_KEY = '3' or WO.WO_TYPE_KEY = '4' or WO.WO_TYPE_KEY = '5') and
(WO.WO_NBR like '' + #workOrder))
ORDER BY WO.WO_NBR
end
((dbo.getDescriptions is a scalar-valued function and works fine))
And here is my xml mapping file in the project:
<select id="listWorkOrder" statementType="CALLABLE" parameterType="WorkOrder" resultMap="WorkOrderMap"> {
call listWorkOrder( #{workOrder, jdbcType=VARCHAR},
#{partNumber, jdbcType=VARCHAR})
}
</select>
Any chance anyone knows what's causing this error? This sql stored procedure breaks both on a remote server we're using and on a local server. Thanks for the assistance!

Why SQL Server complains about non existing column, if the actual SQL is not executed?

I have the following SQL:
IF EXISTS (SELECT 1 FROM sys.columns WHERE name='RequireNamespaceClaim' AND object_id = OBJECT_ID('DefaultBaseUrl'))
BEGIN
UPDATE DefaultBaseUrl SET AuthenticationTypeId = at.AuthenticationTypeId
FROM DefaultBaseUrl dbu
JOIN (
SELECT AuthenticationTypeId, CASE CodeName WHEN 'NATIVE' THEN 0 ELSE 1 END RequireNamespaceClaim
FROM AuthenticationType
) at ON dbu.RequireNamespaceClaim = at.RequireNamespaceClaim
END
Running it prints:
Msg 207, Level 16, State 1, Line 8
Invalid column name 'RequireNamespaceClaim'.
However, running
SELECT 1 FROM sys.columns WHERE name='RequireNamespaceClaim' AND object_id = OBJECT_ID('DefaultBaseUrl')
reveals that no such column indeed exists.
So, the IF EXISTS statement is FALSE, hence the body of the if-statement does not run. However, the error is still printed.
What is going on?
How can I fix it?
SQL Server compiles the entire query and checks it for validity.
At that time the column doesn't exist.
There is a command to run an SQL from a string which is not compiled.
Have a look at (I think that's the right one):
http://technet.microsoft.com/en-us/library/ms175170(v=sql.105).aspx