Pro*C: How to implement Dynamic SQL for inserting data - sql

I'm new to pro*c coding and oracle. I need to insert data into various tables at run time depending on certain condition. Can anyone point me if I can implement the same using dynamic sql method4. Reading through the doc Im really confused.
Oracle doc gave some really nice examples but really confusing. Can anyone point me any simple documents or sites which it is easily understood or any sample code which is easy to understand.
I'm new to this forum, please forgive me if I'm asking too much. And google, I have been doing it this whole day and I'm lost.
Also, There are two types of implementations in method4, ORACLE & ANSI. ANSI seems to be simple method. any suggestion on this?

Here is simple Pro*C snippet to execute Query immediately. Hope you've understood creating contexts.
int OraExecQuery(sql_context *sql_ctx, char *sql_query)
{
/* Error Handling formalities */
EXEC SQL WHENEVER SQLERROR GOTO OracleError;
EXEC SQL CONTEXT USE :sql_ctx;
EXEC SQL EXECUTE IMMEDIATE :sql_query;
EXEC SQL COMMIT;
return (/*Success*/);
OracleError:
/* Handle errors using struct sqlca */
return (/*Failure*/);
}
I too have read manuals from Oracle of necessary versions and did tryouts. On the other hand OCI is tougher to grasp.

Related

good practice with dynamic sql

I use tons of dynamic SQL -
I figured that there must some good guidelines, frameworks and/or tools to help one use dynamic SQL queries.
I'm looking for any suggestions on how exactly should one compose dynamic SQL query (with out the obvious solution of simply writing it, then adding ' ' ect).
The big problem here that sometimes it gets way to messy (dynamic sql that contains another dynamic sql ect).
If it matters at all, I am using sql-server.
I'll take any advice I can get,
Thanks! ;)
Vague question.. But one piece of advice:
Use sp_executesql and pass in any variables/parameters whenever possible to prevent SQL injection
If possible generate the dynamic SQL as much as possible, don't write it yourself.
Execute the dynamic SQL without appending the parameters to the SQL string, use parameters and pass those to sp_executesql to avoid having to do double quoting (too tedious). It is also a solid guard against SQL Injection. Example:
DECLARE #stmt NVARCHAR(MAX)='SELECT * FROM your_table WHERE id=#par1 AND ... AND thename=#parn;';
EXECUTE sp_executesql #stmt, N'#par1 INT, ..., #parn VARCHAR(256)', #par1, ... , #parn;

PostgreSQL why/when should I use ECPG

I've decided to use postgreSQL as database for a game project(C++).
At the moment I'm using Oracle and it's Pro*C precompiler at work and heard that postgreSQL also has something similar called ECPG.
It's also possible to access data from the the postgres database directly by using the SQL in a string.
So the difference between "normal" and using ECPG, is that you can write your SQL statements like code?, or are there any other differences I should be aware of?.
(PS: i know I'm using it at work, but I haven't noticed any other differences)
Looking forward to hearing from you guys.
Yes, ECPG is covered in the documentation.
So the difference between "normal" and using ECPG, is that you can
write your SQL statements like code?
Well, SQL statements are code. A SQL statement just looks like a SQL statement. This is what a CREATE TABLE statement might look like in ECPG.
EXEC SQL CREATE TABLE foo (number integer, ascii char(16));
ECPG allows variable substitution. (Maybe that's what you meant by "write your SQL statements like code".)
EXEC SQL INSERT INTO sometable VALUES (:v1, 'foo', :v2);
All this stuff is in the documentation.

Store Procedures in SQuirrel 3.2.1 when using it with a JDBC driver for a DB2 database

I expend a lot of time trying to retrieve data from a Stored Procedure, here is the code
CREATE PROCEDURE aprocedure(
IN idin CHAR,
OUT returnvalue CHAR)
AS:
SET returnvalue=
(SELECT something
FROM sometable
WHERE id=idin)
I could create it, with no problems, but when I tried to call it like this:
call someprocedure('theid', ?)
Error -313 kept poping out, I did my homework and check the web, IBM forums were no help at all, I couldnt find any documentation, specifications, or anything that make this more clear, also SQL error code -313 means that the number of parameters in the procedure does not match the number of parameters you're using when you call it. So, after too much research, I started thinking that DB2 with JDBC driver and or SQuirreL have trouble when returning OUT values, (I also installed a DB2 CTL client, created a local database, created a table, created the procedure, I called, and everything worked nicely) so I change my code to this (to use a Result Set instead of an OUT):
CREATE PROCEDURE someprocedure(IN idin CHAR (22))
DYNAMIC RESULT SETS 1
P1: BEGIN
DECLARE cursor1 CURSOR WITH RETURN FOR
SELECT something FROM sometable WHERE id=idin;
OPEN cursor1;
END P1
aaaaaaaaaaaand NOTHING, SQuirreL gave me some error codes, when trying to create it, so... I enter that same code in Aqua Data Studio 4.7, and worked like a charm, I call the procedure from Aqua Data like this:
call someprocedure('theid');
and it returned what was supposed to return, I tried that same sentence with SQuirreL...
and it WORKED too !!
Im sure that my sintaxys was correct all along, even with the OUT type of return, so, my question, finally is this.
Does SQuirreL check the input you enter before passing it to the JDBC?
Also
Where do I can find how exactly DB2 is altering SQL code?? because we all know that all DBM change the SQL a bit, but MySQL have great documentation... and i honestly couldnt find any good one on DB2, also im talking about "pure" SQL since in DB2 you can enter stored procedures in C , Java etc...

How can I programmatically run arbitrary SQL statements against my Hibernate/HSQL database?

I'm looking for a way to programmatically execute arbitrary SQL commands against my DB.
(Hibernate, JPA, HSQL)
Query.createNativeQuery() doesn't work for things like CREATE TABLE.
Doing LOTS of searching, I thought I could use the Hibernate Session.doWork().
By using the deprecated Configuration.buildSesionFactory() seems to show that doWork won't work.
I get "use lacks privilege or object not found" for all the CREATE TABLE statements.
So, what other technique is there for executing arbitratry SQL statements?
There were some notes on using the underlying JDBC Statement, but I haven't figure out how to get a JDBC Connection object from Hibernate to try that.
Note that the hibernate.hbm2ddl.auto=create setting will NOT work for me, as I have ARRAY[] columns which it chokes on.
I don't think there is any problem executing a create table statement with a Hibernate native query. Just make sure to use Query.executeUpdate(), and not Query.list() or Query.uniqueResult().
If it doesn't work, please tell us what happens when you execute it, and join the full stack trace of the exception and the SQL query you're executing.
"use lacks privilege or object not found" in HSQL may mean anything, for example existence of a table with the same name. Error messages in HSQL are completely misleading. Try listing your tables using DatabaseMetadata - you have probably already created the table.

Display DataType and Size of Column from SQL Server Query Results at Runtime

Is there a way to run a query and then have SQL Server management studio or sqlcmd or something simply display the datatype and size of each column as it was received.
Seems like this information must be present for the transmission of the data to occur between the server and the client. It would be very helpful to me if it could be displayed.
A little background:
The reason I ask is because I must interface with countless legacy stored procedures with anywhere from 50 to 5000+ lines of code each. I do not want to have to try and follow the cryptic logic flow in and out of temp tables, into other procedures, into string concatenated eval statement and so on. I wish to maintain no knowledge of the implementation, simply what to expect when they work. Unfortunately following the logic flow seems to be the only way to figure out what exactly is being returned without trying to infer what the actual types of the data string representations om management studio studio or from the native type in .net for example.
To clarify: I am not asking about how to tell the types of a table or something static like that. I'm pretty sure something like sp_help will not help me. I am asking how to tell what the sql server types (ie varchar(25), int...) are of what I have been given. Additionally, changing the implementation of the sprocs is not possible so please consider that in your solutions. I am really hoping there is a command I have missed somewhere. Much appreciation to all.
Update
I guess what I am really asking is how to get the schema of the result set when the result set originates from a query using a temp table. I understand this to be impossible but don't find much sense with that conclusion because the data is being transmitted after all. Here is an example of a stored procedure that would cause a problem.
CREATE PROCEDURE [dbo].[IReturnATempTable]
AS
Create table #TempTable
(
MyMysteryColumn char(50)
)
INSERT #TempTable (
MyMysteryColumn
) VALUES (
'Do you know me?' )
select TOP 50 * FROM #TempTable
What will you do about stored procedures which return different result sets based on their parameters?
In any case, you can configure a SqlDataAdapter.SelectCommand, along with the necessary parameters, then call the FillSchema method. Assuming that the schema can be determined, you'll get a DataTable configured with correct column names and types, and some constraints.
A bit of a long shot, try messing around with SET FMTONLY ON (or off). According to BOL, this "Returns only metadata to the client. Can be used to test the format of the response without actually running the query." I suspect that this will inlcude what you're looking for, as BCP uses this. (I stumbled across this setting when debugging some very oddball BCP problems.)
Could you append another select to your procedure?
If so you might be able to do it by using the sql_variant_property function.
Declare #Param Int
Set #Param = 30
Select sql_variant_property(#Param, 'BaseType')
Select sql_variant_property(#Param, 'Precision')
Select sql_variant_property(#Param, 'Scale')
I posted that on this question.
I am asking how to tell what the sql
server types (ie varchar(25), int...)
are of what I have been given
You could then print out the type, precision (i.e. 25 if its VarChar(25)), and the scale of the parameter.
Hope that helps... :)
If you are not limited to T-SQL, and obviously you don't mind running the SPs (because SET FMTONLY ON isn't fully reliable), you definitely CAN call the SPs from, say C#, using a SqlDataReader. Then inspect the SqlDataReader to get the columns and the data types. You might also have multiple result sets, you you can also go to the next result set easily from this environment.
This code should fix you up. It returns a schema only dataset with no records. You can use this Dataset to query the columns' DataType and any other metadata. Later, if you wish, you can populate the DataSet with records by creating a SqlDataAdapter and calling it's Fill method (IDataAdapter.Fill).
private static DataSet FillSchema(SqlConnection conn)
{
DataSet ds = new DataSet();
using (SqlCommand formatCommand = new SqlCommand("SET FMTONLY ON;", conn))
{
formatCommand.ExecuteNonQuery();
SqlDataAdapter formatAdapter = new SqlDataAdapter(formatCommand);
formatAdapter.FillSchema(ds, SchemaType.Source);
formatCommand.CommandText = "SET FMTONLY OFF;";
formatCommand.ExecuteNonQuery();
formatAdapter.Dispose();
}
return ds;
}
I know this is an old question, I found it through a link from SqlDataAdapter.FillSchema with stored procedure that has temporary table. Unfortunately, neither question had an accepted answer, and none of the proposed answers were able to resolve my issue.
For the sake of brevity, if you are using SQL Server 2012 or later, using the following built-in functions will work in most situations:
sys.dm_exec_describe_first_result_set
sys.dm_exec_describe_first_result_set_for_object
However, there are some cases in which these functions will not provide any useful output. In my case, the problem was more similar to the question linked above and therefore, I believe the solution is more appropriately answered under that question. My answer can be found here.