In Snowflake, SQL error handling block fails to execute

Implementing error handling in Snowflake using a Try Catch block has been my focus. I've enclosed SQL queries within JavaScript for this purpose. However, upon executing the query, I noticed that it skips the Try Catch block and directly executes the return statement without running any of the queries inside.

CREATE OR REPLACE PROCEDURE "SP_N_1Test"("STAGE_S3" VARCHAR(16777216), "STAGE_OUTPUT" VARCHAR(16777216))
RETURNS VARCHAR(16777216)
LANGUAGE Javascript
EXECUTE AS CALLER
AS 
$$

var cmd = `truncate table STAGE2A.T001_IRF_STUDENT_FORM_S3`;
var my_sql_command1 = snowflake.createStatement({sqlText: cmd});
var result = my_sql_command1.execute();

var cmd1 = `''COPY INTO STAGE2A.T001_IRF_STUDENT_FORM_S3 
FROM ( select
FN_TrimStr($1) as   State,
FN_TrimStr($2) as   AdminCode,    
from @stage2a.''||:STAGE_S3||'') 
pattern= ''''.*_IRF_.*\\\\.csv''''
file_format = (type=csv, skip_header=1 )''`;
var my_sql_command2 = snowflake.createStatement({sqlText: cmd1});
var result1 = my_sql_command2.execute();

var cmd2 = `Insert into STAGE2B.T011_IRF_STUDENT_FORM_V001 (
   STATE_FLAG,
    STATE_CD,
    )
SELECT
   STATE_FLAG,
    STATE_CD,
    from  STAGE2A.V001_IRF_STUDENT_FORM_T001`;
var my_sql_command3 = snowflake.createStatement({sqlText: cmd2});
var result2 = my_sql_command3.execute();

return;
$$;

In addition to this issue, I have also tried to include a message in each Try block to indicate success when it runs successfully. However, attempts with

Print, Println, sustem.print.out()
do not seem to work.

Answer №1

It appears there is some confusion regarding the execution of SQL statements within the procedure. To properly execute SQLs, the snowflake API needs to be utilized:

Upon review, it seems that backticks (`) were used incorrectly in the code snippet provided. The premature closing of backticks turned everything into a template string and caused the function to return immediately. It is essential to learn how to correctly utilize the snowflake API for executing SQL commands.

In terms of generating an output, it is not feasible to output data in the manner shown in the code. Instead, a variable can be defined to hold the output or logs can be inserted into a table.

CREATE OR REPLACE PROCEDURE sp_test("STAGE_S3" VARCHAR(16777216), "STAGE_OUTPUT" VARCHAR(16777216))
RETURNS VARCHAR(16777216)
LANGUAGE Javascript
EXECUTE AS CALLER
AS 
'
var result = "";

try{ `truncate table "STAGE2A"."T001_IRF_STUDENT_FORM_S3"`;
   result += "table truncated ";
}
catch (err){}
...
result += "Load process completed for IRF_STUDENT_FORM_S3";

}

catch(err){}

return result; 
';

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using NodeJS to Send JSON Data via HTTP POST Request

Issue with Sending JSON Data via Http Post in NodeJS const http = require('http'); const fs = require('fs'); var options = { hostname: 'www.postcatcher.in', port: 80, path: '/catchers/5531b7faacde130300002495&apo ...

Retrieve data from Postgres by querying for rows where the json column contains more than one array element in the json data

We are currently utilizing a Postgres database where we have a table with a column of type JSON. The format of the JSON data is as follows: { "name" : "XXX", "id" : "123", "course" :[ { "name" : "java", "tutor":"YYYY" }, ...

The issue of Angular's ng-repeat view not refreshing after a search query remains unresolved

Having some trouble with updating a results array in AngularJS using a service call. After submitting a form and calling the service, I set up my callbacks with .then() on the promise object. However, the view only updates when I start deleting characters ...

As the height is expanded, the background color gradually infiltrates the body of the page

I am currently working on an angular application that utilizes angular-pdf. The controller and view function perfectly, and the PDF is displayed correctly, except for one issue. The height of the PDF exceeds the min-height of the module, causing it to expa ...

How can you display an alert message when new data is successfully added to a database using ajax?

In my web application, I have implemented a functionality to display an alert message when new data is successfully inserted into the database. The Ajax code below is responsible for sending a request to the EditDeleteLecture.php file. However, a challenge ...

Guide for setting up a React infinite scroll feature in a messaging app similar to Facebook Messenger

I have been exploring various questions regarding React infinite scroll, but I am looking to delve deeper in order to discover the most effective solution available for implementing such a component. Currently, I am working on a chat application and have ...

Looking for a drag-and-drop solution using Vanilla Javascript, no need for jQuery

Looking for assistance with creating a click-and-drag solution for a background image using Vanilla Javascript. I came across a jQuery solution on Codepen, but I need help translating it into Vanilla Javascript. Draggable.create(".box", { ...

Character count in textarea does not work properly when the page is first loaded

As English is not my first language, I apologize in advance for any grammar mistakes. I have implemented a JavaScript function to count the characters in a textarea. The code works perfectly - it displays the character limit reducing as you type. However, ...

Using async/await in an Express route handler

Currently, I am facing an issue with my node/express route. The route collects information through url parameters and then uses these parameters to trigger a separate function that takes some time to execute. Despite using async/await to pause the executio ...

I am experiencing issues with the middleware not functioning properly after implementing a custom application with Next.js

I'm currently diving into Next.js version 13 and attempting to customize the app based on the standard documentation. However, it seems that the middleware isn't being invoked as expected. I suspect there might be something wrong with my implemen ...

NuxtJS using Babel 7: the spread operator persists in compiled files

Struggling to get my NuxtJS app functioning properly on IE11. Despite multiple attempts to configure Babel for compatibility, spread operators are still present in the built pages files, suggesting that Nuxt code is not being transformed correctly. Below ...

Inject Angularjs Controller into Module Once DOM is Initialized: Tips and Tricks

When injecting new DOM elements with a controller, I encountered the following issue: app.controller('cart', function ($scope, $http) { $scope.content = { label: "hello, world!", }; }); var $html = '<div ng-controller="c ...

What is the best way to distribute components between two NextJS projects?

Confused about the best way to share ReactJs components between two NextJs applications - one for e-commerce and the other for a manager portal. In the e-commerce app, there are various UI components that I want to reuse in the manager portal. Considering ...

What is the best approach to determine the numerical equivalents of options in a dropdown menu using PHP and JS

Hey guys, I'm really stuck on this problem and I can't seem to find a helpful tutorial anywhere. I've got a form with two drop-down menus, each with a "value" attribute. What I want is for users to be able to select an item from both drop-do ...

What is causing `foo()` to function in this specific scenario?

Check out this code snippet: https://jsfiddle.net/5k10h27j/ I'm puzzled by why foo() is being called as an argument to a non-existent function. function foo(){ alert('huh??'); } jQuery('#container').on('change', ...

Implementing Express 4: The Correct Way to Serve Routes from External Files

Something about my Express 4 application is causing me frustration. Here's the configuration: routes/profile.js var express = require('express'); var router = express.Router(); router.get('/profile', function(req, res) { res.s ...

Consistently Encountering The 404 Error

Greetings! Below is the code snippet from my app.js: var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require(& ...

JavaScript: Accessing the selectedIndex of a dropdown list in RadGrid

Currently facing an issue with utilizing the RadGrid control from Telerik. I am attempting to access and manipulate the value of a GridDropDowncolumn within RadGrid using JavaScript (while in edit mode). Does anyone have any suggestions for the correct Ja ...

Alert: A notification when navigating away from your site

Is there a way to notify users when they click on an external link that they are leaving your site? <div class="row"> <div class="col-lg-12"> <div class="form-group"> *If you need information on other applicable forms, you ...

Angular JS failing to display error messages

I'm experiencing difficulties displaying login validation errors with the following code. After clicking on the Login button, it redirects to the next page without showing error messages as expected. Any suggestions? index.html:- <!DOCTYPE ht ...