Dynamic cursor PERVASIVE - cursor

I'm trying to create SP with dynamic cursor for obtain the result of any Select statement
CREATE PROCEDURE CursorTest (:query IN VARCHAR(5000)) ;
BEGIN
DECLARE :out VARCHAR;
DECLARE :dynamicCursor CURSOR FOR EXEC (:query);
OPEN dynamicCursor;
/* cursor loop */
Cursorloop:
LOOP
FETCH NEXT FROM `enter code here`Cursorloop INTO :out;
End LOOP;
CLOSE dynamicCursor;
END;
I have 2 problems on that, Declare the cursor with the dynamic query and output the result as a row.
Thanks in advance

Since this question is tagged pervasive I'm assuming you want to achieve this in PervasiveSQL.
I don't think what you are trying to do is possible there. The main reason for this is that - to my knowledge - P-SQL has no aggregate functions to combine arbitrary columns or rows into a string (like e.g. PostgreSQL's string_agg).
Secondly, P-SQL does not support querying by column number. The :query argument can be any statement (even an invalid one!), so you don't know how many columns it'll produce.
On a more essential note: what is it exactly that you want to achieve? This stored procedure looks to me like an overly complicated way of just executing :query, and having no means of handling the result. If logging or analysis is your goal, wouldn't you be better off by using an external, more flexible (scripting) language to deal with the result set? Admittedly SQL is a programming language, but it has its limitations.

Related

Accessing to OUT parameter (t_cursor type) from stored procedure using go and InstantClient

I'm dealing with an Oracle DB, connecting from go via InstantClient (version 11) (https://github.com/mattn/go-oci8). I need to be able to load this object and browse results... t_cursor output parameter.
I have tried many strategies, I know how to map function parameters to go structures but I don't know how to work with t_cursor type since it seems not being implemented in InstantClient
Example of stored procedure
create or replace procedure EXAMPLE(a IN NUMBER, b IN NUMBER, c OUT T_CURSOR) AS BEGIN
[Edit] We have also tried to execute SQL blocks from code to try to handle this third parameter.
i.e.
If you add something like
declare
c t_cursor;
begin
EXAMPLE(:1, :2, c)
end
then I don't know how you can get the block to return a result set that contains the cursor.
declare
c t_cursor;
begin
EXAMPLE(:1, :2, c)
select 1, c from dual
end
The whole block returning the result of that select would be ideal but oracle blocks do not return result sets afaik.
Anyone who can bear a hand on this?
Thank you very much
It can be done with the driver https://github.com/rana/ora instead.
*Rset may be passed to Stmt.Exe when prepared with a stored procedure accepting an OUT SYS_REFCURSOR
The README.me even has that exact example.
Caveats:
It's unclear whether the database/sql interface may be used or you are limited to the lib specific API.
Instant Client gets restricted to versions from 12.1.0.1.0 on.

DECIMAL Index on CHAR column

I am dealing with some legacy code that looks like this:
Declare #PolicyId int
;
Select top 1 #PolicyId = policyid from policytab
;
Select col002
From SOMETAB
Where (cast(Col001 as int) = #PolicyId)
;
The code is actually in a loop, but the problem is the same. col001 is a CHAR(10)
Is there a way to specify an index on SOMETAB.Col001 that would speed up this code?
Are there other ways to speed up this code without modifying it?
The context of that question is that I am guessing that a simple index on col001 will not speed up the code because the select statement doing a cast on the column.
I am looking for a solution that does not involve changing this code because this technique was used on several tables and in several scripts for each table.
Once I determine that it is hopeless to speed up this code without changing it I have several options. I am bringing that so this post can stay on the topic of speeding up the code without changing the code.
Shortcut to hopeless if you can not change the code, (cast(Col001 as int) = #PolicyId) is not SARGable.
Sargable
SARGable functions in SQL Server - Rob Farley
SARGable expressions and performance - Daniel Hutmachier
After shortcut, avoid loops when possible and keep your search arguments SARGable. Indexed persisted computed columns are an option if you must maintain the char column and must compare to an integer.
If you cannot change the table structure, cast your parameter to the data type you are searching on in your select statement.
Cast(#PolicyId as char(10)) . This is a code change, and a good place to start looking if you decide to change code based on sqlZim's answer.
Zim's advice is excellent, and searching on int will always be faster than char. But, you may find this method an acceptable alternative to any schema changes.
Is policy stored as an int in PolicyTab and char in SomeTab for certain?

Converting dbase do while to sql

I wrote a dBase procedure and I'm having a hard time converting it to a SQL Server stored procedure.
This is what I have for dbase:
CLOSE ALL
SELECT A
USE DDCS_OLD
SELECT B
USE CROSSELL
DO WHILE .NOT. EOF()
mLAT1 = IND_LAT
mLONG1 = IND_LONG
IF mLAT1 > 0 .AND. mLONG1 < 0
SELECT A
GOTO TOP
DO WHILE .NOT. EOF()
mLAT2 = LAT
mLONG2 = LONG
mPROP_CODE = PROP_CODE
mDISTANCE = 3963.0 * ACOS(SIN(mLAT1/57.2958) * SIN(mLAT2/57.2958) + COS(mLAT1/57.2958) * COS(mLAT2/57.2958) * COS(mLONG2/57.2958 - mLONG1/57.2958))
SELECT B
REPLACE &mPROP_CODE WITH mDISTANCE
SELECT A
SKIP
ENDDO
ENDIF
SELECT B
SKIP
END DO'
I have never written a stored procedure before so I'm not sure how to go about a do while loop while using the two tables ddcs_old and crossell.
That looks like a tremendously complicated calculation that I would consider moving out of the database and into the application that is using this data, if at all possible.
However, I'm guessing that what DO WHILE .NOT. EOF() does in dbase is basically read one row at a time from the table, until it reaches the end. In a SQL Stored Procedure you would achieve this with a cursor:
DECLARE crDDCS_Old CURSOR LOCAL FORWARD_ONLY FOR
SELECT LAT, LONG, PROP_CODE FROM ddcs_old
OPEN crDDCS_Old
FETCH NEXT FROM crDDCS_Old
WHILE ##FETCH_STATUS = 0
BEGIN
-- Do your calculations here
FETCH NEXT FROM crDDCS_Old
END
CLOSE crDDCS_Old
DEALLOCATE crDDCS_Old
As I said, I would strongly recommend reconsidering the best way of implementing this functionality, a direct conversion to a stored procedure is highly unlikely to be the best approach. Cursors are inefficient and, apparently, more lines of code than the dbase equivalent. You'd need in-depth knowledge of what it was doing in dbase and how that data is being used, to come up with the best alternative.
You don't use sql like DBase. If at all possible, you want to execute any operation using a set based operation that update all corresponding rows with a single update command -- I.e., you avoid loops based on a cursor 99.97% of the time. Also, without column definitions for your DBase tables (and hopefully corresponding columns for your SQL tables), I don't know how you expect to get any help as it is not really possible to figure out what your existing code does.
However it also looks a like you you are doing great circle calculations, beginning in Sql 2008, you can use the geography data type, which has build in functions for a number of geographic features, including great circle distances.
You really need to get a little understanding of how SQL works instead of asking for some magic and opaque answer -- the time will be well spent and when you get stuck, S/O is a good source for getting unstuck.
I know this is more of a comment, but it is too long for a comment.

How to declare local variables in postgresql?

There is an almost identical, but not really answered question here.
I am migrating an application from MS SQL Server to PostgreSQL. In many places in code I use local variables so I would like to go for the change that requires less work, so could you please tell me which is the best way to translate the following code?
-- MS SQL Syntax: declare 2 variables, assign value and return the sum of the two
declare #One integer = 1
declare #Two integer = 2
select #One + #Two as SUM
this returns:
SUM
-----------
3
(1 row(s) affected)
I will use Postgresql 8.4 or even 9.0 if it contains significant fetaures that will simplify the translation.
Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.
In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:
CREATE OR REPLACE FUNCTION somefuncname() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
one int;
two int;
BEGIN
one := 1;
two := 2;
RETURN one + two;
END
$$;
SELECT somefuncname();
The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.

T-SQL Where Clause Case Statement Optimization (optional parameters to StoredProc)

I've been battling this one for a while now. I have a stored proc that takes in 3 parameters that are used to filter. If a specific value is passed in, I want to filter on that. If -1 is passed in, give me all.
I've tried it the following two ways:
First way:
SELECT field1, field2...etc
FROM my_view
WHERE
parm1 = CASE WHEN #PARM1= -1 THEN parm1 ELSE #PARM1 END
AND parm2 = CASE WHEN #PARM2 = -1 THEN parm2 ELSE #PARM2 END
AND parm3 = CASE WHEN #PARM3 = -1 THEN parm3 ELSE #PARM3 END
Second Way:
SELECT field1, field2...etc
FROM my_view
WHERE
(#PARM1 = -1 OR parm1 = #PARM1)
AND (#PARM2 = -1 OR parm2 = #PARM2)
AND (#PARM3 = -1 OR parm3 = #PARM3)
I read somewhere that the second way will short circuit and never eval the second part if true. My DBA said it forces a table scan. I have not verified this, but it seems to run slower on some cases.
The main table that this view selects from has somewhere around 1.5 million records, and the view proceeds to join on about 15 other tables to gather a bunch of other information.
Both of these methods are slow...taking me from instant to anywhere from 2-40 seconds, which in my situation is completely unacceptable.
Is there a better way that doesn't involve breaking it down into each separate case of specific vs -1 ?
Any help is appreciated. Thanks.
I read somewhere that the second way will short circuit and never eval the second part if true. My DBA said it forces a table scan.
You read wrong; it will not short circuit. Your DBA is right; it will not play well with the query optimizer and likely force a table scan.
The first option is about as good as it gets. Your options to improve things are dynamic sql or a long stored procedure with every possible combination of filter columns so you get independent query plans. You might also try using the "WITH RECOMPILE" option, but I don't think it will help you.
if you are running SQL Server 2005 or above you can use IFs to make multiple version of the query with the proper WHERE so an index can be used. Each query plan will be placed in the query cache.
also, here is a very comprehensive article on this topic:
Dynamic Search Conditions in T-SQL by Erland Sommarskog
it covers all the issues and methods of trying to write queries with multiple optional search conditions
here is the table of contents:
Introduction
The Case Study: Searching Orders
The Northgale Database
Dynamic SQL
Introduction
Using sp_executesql
Using the CLR
Using EXEC()
When Caching Is Not Really What You Want
Static SQL
Introduction
x = #x OR #x IS NULL
Using IF statements
Umachandar's Bag of Tricks
Using Temp Tables
x = #x AND #x IS NOT NULL
Handling Complex Conditions
Hybrid Solutions – Using both Static and Dynamic SQL
Using Views
Using Inline Table Functions
Conclusion
Feedback and Acknowledgements
Revision History
If you pass in a null value when you want everything, then you can write your where clause as
Where colName = IsNull(#Paramater, ColName)
This is basically same as your first method... it will work as long as the column itself is not nullable... Null values IN the column will mess it up slightly.
The only approach to speed it up is to add an index on the column being filtered on in the Where clause. Is there one already? If not, that will result in a dramatic improvement.
No other way I can think of then doing:
WHERE
(MyCase IS NULL OR MyCase = #MyCaseParameter)
AND ....
The second one is more simpler and readable to ther developers if you ask me.
SQL 2008 and later make some improvements to optimization for things like (MyCase IS NULL OR MyCase = #MyCaseParameter) AND ....
If you can upgrade, and if you add an OPTION (RECOMPILE) to get decent perf for all possible param combinations (this is a situation where there is no single plan that is good for all possible param combinations), you may find that this performs well.
http://blogs.msdn.com/b/bartd/archive/2009/05/03/sometimes-the-simplest-solution-isn-t-the-best-solution-the-all-in-one-search-query.aspx

Resources