PHP PDO MSSQL - Aborting DB transaction in query which raisses error with severity 0 (warnings) - pdo

I am creating web app in Laravel which connects to MSSQL DB (using PDO) and i'm stuck with a issue when running query (UPDATE in my case)
update dba.[vl_zahlavi] set [xcmd] = ' AFTERCOMMIT', [vl_zahlavi].[ts] = '2023-01-10 14:16:06.505' where [doklad] = '23VLTU0100000001'
which raises error with severity 0 within update trigger (used for sending progress bar information to client). Trigger is created within information system, so I'm not able to disable this functionality.
select #progress_count = convert(int/*BY*/,#akt_pocet), #progress_current = 0, #progress_dt_o_skl_o_skl_gen_poh_prub = DateAdd(ms, -1000, GetDate())
select #progress_arg = '#SQL_PROGRESS=O_SKL,O_SKL_GEN_POH_PRUB,' + convert(varchar(255)/*BY*/, ##nestlevel) + ',OPEN,' + convert(varchar(255)/*BY*/, #progress_count) + ';'
RAISERROR ('%s', 0, 1, #progress_arg) WITH NOWAIT
Problem is, that PHP client send abort and transaction is automatically rolled back. When I comment this section of code (or change severity to 16), everything works as expected. Bellow is printscreen from SQL server profiler.
printscreen
Is PDO able to catch user error messages?
Thank you in advance.
I have tried to change DB sets and PDO options, but without success.

Related

Executing SQL Script causes error in procedure called by trigger

I'm also new to DevOps, but let me see if I can explain my situation, also if anyone has any advice on doing post deployment scripts and can share their experiences I will be most grateful.
I use SQL Source control from Redgate, Git and Azure DevOps. I have managed to get the build and deployment working perfectly. Additionally we would like to make some data changes so we have additional (Data Change) scripts we wish to run. Linking these tables as static data is not an option as we would end up having most tables linked and end up with extremely timeous build and deploy times.
The script inserts data to a table, thereby triggering the insert trigger which calls a procedure to write to an audit table. The actual error from the deployment log is:
Task : DbUp Migration
2021-01-25T12:52:17.2629353Z Description : Runs SQL Server change scripts, and only those which have not been run already.
2021-01-25T12:52:17.2629405Z Version : 2.1.4
2021-01-25T12:52:17.2629671Z Author : Johan Classon
2021-01-25T12:52:17.2629721Z Help : [More Information](https://github.com/johanclasson/vso-agent-tasks)
2021-01-25T12:52:17.2629775Z ==============================================================================
2021-01-25T12:52:19.6610608Z Beginning database upgrade
2021-01-25T12:52:19.6689401Z Checking whether journal table exists..
2021-01-25T12:52:19.6728756Z Journal table does not exist
2021-01-25T12:52:19.7775348Z Executing Database Server script '001 - EX27605 - rdl.sql'
2021-01-25T12:52:19.7908913Z Checking whether journal table exists..
2021-01-25T12:52:19.7929056Z Creating the [dbo].[_SchemaVersions] table
2021-01-25T12:52:19.8077238Z The [dbo].[_SchemaVersions] table has been created
2021-01-25T12:52:20.2264323Z ifExists - rdl_Rule_Definition_Lookup - rdl_Code = "9900226e"
2021-01-25T12:52:20.2277308Z insert - rdl_Rule_Definition_Lookup - rdl_Code = "9900226e"
2021-01-25T12:52:20.2805780Z SQL exception has occured in script: '001 - EX27605 - rdl.sql'
2021-01-25T12:52:20.2942912Z ##[error]Script block number: 0; Block line 74; Message: Trig_After_Ins_Upd_Del_rdl_Rule_Definition_Lookup
2021-01-25T12:52:20.4528752Z ##[error]System.Data.SqlClient.SqlException (0x80131904): p_dte_Audit_Backend: (Line: 108) [dte_admin]
So the 1st error refers to line 74 of the trigger, if I read this correctly which is a commit on a procedure call to write to the audit table, line 108 of my procedure sets the userID:
DECLARE #user VARCHAR(40)
SET #user =
CASE
WHEN suser_sname() = 'NT SERVICE\SQLAgent$'+##servicename THEN 'dte_admin'
WHEN suser_sname() = 'NT SERVICE\SQLSERVERAGENT' THEN 'dte_admin'
ELSE suser_sname()
END
--###############
select #udt_Audit = udt_Audit
from udt_User_Detail (nolock)
where udt_User_Id = #user--suser_sname()
--select #udt_Audit = udt_Audit from udt_User_Detail
--where udt_User_Id = suser_sname()
if ##rowcount = 0
begin
declare #udt_User_Id varchar(30)
set #udt_User_Id = suser_sname()
The last line being line 108.
Important to note that dte_admin is a login on the SQL Server, it is a sysadmin account and mapped to the database, the dte_admin user is also a user at database level and exists as a user in my user table udt_user_detail.
During the build and deployment I am using variables and they are set to dte_admin username and password.
My question is then, why does this fail with this user?
Deployment Pipeline result

How to debug an intemittent error using Progress OpenEdge database

I have a program that fails intermittently in a complex query.
The error reads:
System.Data.SqlClient.SqlException: Cannot fetch a row from OLE DB provider "MSDASQL" for linked server "LinkedServer".
The query looks like this:
SELECT Replace([JOB-NO],'M0','') as KeyTaskID,
dbo.SFGET_UniqueTaskID([CLIENT-CODE],Replace([JOB-NO], 'M0', ''), 0, [TRADE-CODE]) AS HMSUniqueTaskID,
[LATEST-PRIORITY] AS PriorityCode,
[KeyProperty] AS KeyProperty,
Replace([JOB-NO],'M0','') AS KeyJob,
[JOB-TYPE] as TaskSubType,
CONVERT(varchar(6),[MAINT-OFFICER]) AS Officer,
LEFT(FORENAME + ' ' + SURNAME, 50) AS OfficerName,
[JOB-NO] + ' ' + LEFT(RTRIM(REPLACE([TEXT-LINE], ';', CHAR(13))), 480) AS Description,
dbo.SFGET_FormattedDate([TARGET-DATE],0) AS DueDateTime,
[CURRENT-STAGE-CODE] AS CurrentStageCode
FROM openquery(LinkedServer, '
SELECT DISTINCT
"RM-JOB"."JOB-NO",
"RM-JOB"."CLIENT-CODE",
"RM-JOB"."LATEST-PRIORITY",
"RM-JOB"."TRADE-CODE",
"RM-JOB"."JOB-TYPE",
"RM-JOB"."TARGET-DATE",
"RM-JOB"."MAINT-OFFICER",
"RM-JOB"."TEXT-LINE",
"RM-JOB"."CURRENT-STAGE-CODE",
"RM-JOB"."PLACE-REF",
"IH_OFFICER".FORENAME,
"IH_OFFICER".SURNAME
FROM "PUB"."RM-JOB"
LEFT OUTER JOIN "PUB"."IH_OFFICER"
ON ("IH_OFFICER"."OFFICER-CODE" = "RM-JOB"."MAINT-OFFICER")
WHERE "RM-JOB"."JOB-TYPE" = ''GASS''
AND "RM-JOB"."JOB-STATUS" = 06
AND "RM-JOB"."CONTRACTOR" = ''NWH001'' ') as ibsTasks
INNER JOIN [SVSExtract].[dbo].Property prop
ON ibsTasks.[PLACE-REF] = prop.UserCode
I have been testing it manually using SQL Server Management Studio. It occassionally fails but it mainly works OK.
I am at a loss as to how I can debug an error that I cannot reproduce at will.
Any suggestions?
I'm not that proficient in SqlClients and Progress myself but: the Progress Knowledgebase might give you a solution!
This entry for instance describes a similar error, even if the version mentioned might be older than the one you use? (Always post version when asking about OpenEdge - there's lots of older installations out there and Progress has evolved quite a bit during the last couple of years).
The Knowledgebase is honestly best searched using Google:
Search for instance: site:knowledgebase.progress.com MSDASQL and you'll get 48 results.

SQL Server OLEDB error with no details

I have a SQL Server Agent job running, which uses a stored procedure to do several operations, then exports some data to an xls spreadsheet and emails that spreadsheet. Most of the time it works, but several times a month the job fails with the error:
OLE DB provider 'Microsoft.Jet.OLEDB.4.0' reported an error. The provider did not give any information about the error. [SQLSTATE 42000] (Error 7399). The step failed.
Thanks, Microsoft, for the detailed error message. Anyway, the short term fix is usually to simply re-run the job. Usually this works, but in rarer cases it does not, and I must restart the SQL Server instance.
Here is how my code interacts with OLEDB:
Insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel 5.0;Database=\\Excel\POStatus\POStatus.xls;',
'SELECT * FROM [POStatus$]')
Select --Tons of columns with tons of math and functions
FROM --5 tables joined together (left joins)
WHERE -- Tons of where conditions
Order by --Case statement for custom sorting
Set #vCommand = 'copy \\Excel\POStatus\POStatus.xls \\Excel\POStatus\POStatus_' + #vDate + '.xls'
EXEC master..xp_cmdshell #vCommand , NO_OUTPUT
... omitted for brevity...
Set #nvSubject = ' POStatus ' + #vDate
Set #nvMessage = ' This is an automated message, please respond to the IS department, thank you '
Set #nvMessage = #nvMessage + char(13) + char(10)
Set #nvAttachments = '\\Excel\POStatus\POStatus_' + #vDate + '.xls'
Exec master..xp_sendmail
#recipients = #nvRecipients , #copy_recipients = #nvCopy_recipients ,
#subject = #nvSubject , #message = #nvMessage ,
#query = #nvQuery , #width = #iWidth , #attachments = #nvAttachments
So, what is the cause of this, and how can I prevent it?
When you call OPENROWSET, it load the DLL for OLEDB provider for Excel. These operations happens inside the SQL Server Stack memory. When a lot of call to older DLL (ActiveX/COM) are made, it's not impossible that your stack might get full. You can resolve this in 2 ways:
1) You make these operations outside a TSQL code. You can use a SSIS package for example but you have to change your code not to use OPENROWSET. You can use the DTS Wizard to do most of the job. This is my personnal recommandation !
2) You can also set SQL Server to have a bigger memory Stack by using the -g command parameter. I think 256 MB is the default and you can set it to 512. To do that you need to open the SQL Server Configuration Manager. Depending on your version, you should have a place to change the "Startup Parameters"

Would like help with LOGON Trigger

I've created a logon trigger in MS SQL that needs to check dm_exec_sessions for a login. This login is the user listed in the connection string and has owner right to the database. If the login is verified, I need it to update a specific table and send an email.
So far I've done just the following piece and it disabled my web site. The error I get is: "Logon failed for login 'dev' due to trigger execution. Changed database context to 'mydatabase'. Changed language setting to us_english."
Any idea what I did wrong? Thanks,
Risho
CREATE TRIGGER TDY_Assets_Notification
ON ALL SERVER WITH EXECUTE AS 'dev'
FOR LOGON
AS
BEGIN
IF ORIGINAL_LOGIN()='dev' AND
(SELECT COUNT(*) FROM sys.dm_exec_sessions
WHERE is_user_process = 1 AND
original_login_name = 'dev') > 1
UPDATE Assets_TDY
SET Suspense = 1, Warning = 1
WHERE (Date_Returned IS NULL) AND (GETDATE() >= DATEADD(day, 3, Date_Return))
END
Try connecting with the Dedicated Administrator Connection. That will give you an opportunity to disable the faulty logon trigger.
DISABLE TRIGGER [TDY_Assets_Notification] ON ALL SERVER

SQL Server Agent 2005 job runs but no output

Essentially I have a job which runs in BIDS and as as a stand lone package and while it runs under the SQL Server Agent it doesn't complete properly (no error messages though).
The job steps are:
1) Delete all rows from table;
2) Use For each loop to fill up table from Excel spreasheets;
3) Clean up table.
I've tried this MS page (steps 1 & 2), didn't see any need to start changing from Server side security.
Also SQLServerCentral.com for this page, no resolution.
How can I get error logging or a fix?
Note I've reposted this from Server Fault as it's one of those questions that's not pure admin or programming.
I have logged in as the proxy account I'm running this under, and the job runs stand alone but complains that the Excel tables are empty?
Here's how I managed tracking "returned state" from an SSIS package called via a SQL Agent job. If we're lucky, some of this may apply to your system.
Job calls a stored procedure
Procedure builds a DTEXEC call (with a dozen or more parameters)
Procedure calls xp_cmdshell, with the call as a parameter (#Command)
SSIS package runs
"local" SSIS variable is initialized to 1
If an error is raised, SSIS "flow" passes to a step that sets that local variable to 0
In a final step, use Expressions to set SSIS property "ForceExecutionResult" to that local variable (1 = Success, 0 = Failure)
Full form of the SSIS call stores the returned value like so:
EXECUTE #ReturnValue = master.dbo.xp_cmdshell #Command
...and then it gets messy, as you can get a host of values returned from SSIS . I logged actions and activity in a DB table while going through the SSIS steps and consult that to try to work things out (which is where #Description below comes from). Here's the relevant code and comments:
-- Evaluate the DTEXEC return code
SET #Message = case
when #ReturnValue = 1 and #Description <> 'SSIS Package' then 'SSIS Package execution was stopped or interrupted before it completed'
when #ReturnValue in (0,1) then '' -- Package success or failure is logged within the package
when #ReturnValue = 3 then 'DTEXEC exit code 3, package interrupted'
when #ReturnValue in (4,5,6) then 'DTEXEC exit code ' + cast(#Returnvalue as varchar(10)) + ', package could not be run'
else 'DTEXEC exit code ' + isnull(cast(#Returnvalue as varchar(10)), '<NULL>') + ' is an unknown and unanticipated value'
end
-- Oddball case: if cmd.exe process is killed, return value is 1, but process will continue anyway
-- and could finish 100% succesfully... and #ReturnValue will equal 1. If you can figure out how,
-- write a check for this in here.
That last references the "what if, while SSIS is running, some admin joker kills the CMD session (from, say, taskmanager) because the process is running too long" situation. We've never had it happen--that I know of--but they were uber-paranoid when I was writing this so I had to look into it...
Why not use logging built into SSIS? We send our logs toa database table and then parse them out to another table in amore user friendly format and can see every step of everypackage that was run. And every error.
I did fix this eventually, thanks for the suggestions.
Basically I logged into Windows with the proxy user account I was running and started to see errors like:
"The For each file enumerator is empty"
I copied the project files across and started testing, it turned out that I'd still left a file path (N:/) in the properties of the For Each loop box, although I'd changed the connection properties. Easier once you've got error conditions to work with. I also had to recreate the variable mapping.
No wonder people just recreate the whole package.
Now fixed and working!