Build stored procedure from a dynamic SQL query
I have the following method, that receives a string from a textbox and creates a dynamic select command. Since I am using a dataSet I cannot execute a dynamic SQL query by calling a method of a strongly-typed dataset (.xsd). I have been told that the best
way to do this is to pass an array of values to the stored procedure.
But I have no clue how to build the stored procedure.
string[] allWords = txtSearch.Text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
string sql = "SELECT Books.ISBN, Books.Title, Books.Tag, Books.Image, Books.photoType, Publishers.Name AS publisherName FROM Books INNER JOIN Publishers ON Books.codPublisher = Publishers.codPublisher WHERE ";
using (SqlCommand command = new SqlCommand())
for (int i = 0; i < allWords.Length; ++i)
if (i > 0)
sql += "OR ";
string paramName = "@param" + i.ToString();
sql += string.Format("(Books.Title LIKE {0}) ", paramName);
command.Parameters.AddWithValue(paramName, allWords[i] + "%");
command.CommandText = sql;
//execute the SQL query against the db...
After hours around this, I have came with this solution.
private SqlConnection sqlConn = new SqlConnection();
private System.Data.DataSet dataSet = new System.Data.DataSet();
private System.Data.DataTable dataTable;
private System.Data.DataRow dataRow;
private SqlCommand search(string searchParam, int searchOption)
SqlCommand command = new SqlCommand();
string sql;
string[] allWords = searchParam.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (searchOption == 1)
sql = "SELECT Livros.ISBN, Livros.Titulo, Livros.Tema, Livros.Resumo, Livros.Imagem, Livros.fotoTipo, Editoras.Nome AS nomeEditora FROM Livros INNER JOIN Editoras ON Livros.codEditora = Editoras.codEditora WHERE ";
else
sql = "SELECT Livros.ISBN, Livros.Titulo, Livros.Tema, Livros.Resumo, Livros.Imagem, Livros.fotoTipo, Editoras.Nome AS nomeEditora FROM Livros INNER JOIN livrosAutores ON Livros.ISBN = livrosAutores.ISBN INNER JOIN Autores ON livrosAutores.idAutor = Autores.idAutor INNER JOIN Editoras ON Livros.codEditora = Editoras.codEditora WHERE ";
using (command)
for (int i = 0; i < allWords.Length; ++i)
if (i > 0)
sql += "OR ";
if (searchOption == 1)
sql += string.Format("(Livros.Titulo LIKE '%{0}%') ", allWords[i]);
else
sql += string.Format("(Livros.Autor LIKE '%{0}%') ", allWords[i]);
command.CommandText = sql;
return command;
protected void Bind()
sqlConn.ConnectionString = Properties.Settings.Default.BibliotecaConnectionString;
string connectionString = sqlConn.ConnectionString.ToString();
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(search(searchText, searchOption).CommandText, connectionString);
sqlDataAdapter.Fill(dataSet, "livrosTitulo");
dataTable = dataSet.Tables["livrosTitulo"];
dataGrid.DataContext = dataTable.DefaultView;
Similar Messages
-
Error while executing java stored procedure from a pl/sql procedure
We have a requirement where we need to execute JAVA code stored in an Oracle database (Java Stored Procedure). This code uses some JAR files which we have already loaded without any errors in the database.
The class file was also loaded in the database without any errors. But when we execute the method of this class (JAVA code), it gives the following error:
ORA-29532: Java call terminated by uncaught Java exception:
java.lang.NoClassDefFoundError
Is there any way of debugging the code and getting to know where exactly the problem is? Or, any tool/software available for doing the same.
Any pointers would be of great help!
Thanks in advanceHi Uday,
My guess is that there is a problem with your java stored procedure that is causing the "ExceptionInInitializer" error to be thrown. According to the javadoc:
is thrown to indicate that an exception occurred during
evaluation of a static initializer or
the initializer for a static variable
Since I didn't see any of your code in your post, I can't help you much more, I'm afraid. Perhaps if you would provide some more details, I may be able to help you some more. I think the following details would be helpful:
1. Complete error message and stack trace you are getting.
2. The section of your java code that you think is causing the problem.
3. Oracle database version you are using.
Good Luck,
Avi. -
How to get save result from EXECUTE from a dynamic SQL query in another table?
Hi everyone,
I have this query:
declare @query varchar(max) = ''
declare @par varchar(10)
SELECT @par = col1 FROM Set
declare @region varchar(50)
SELECT @region = Region FROM Customer
declare @key int
SELECT @key = CustomerKey FROM Customer
SET @query = 'SELECT CustomerKey FROM Customer where ' + @par + ' = '+ @key+ ' '
EXECUTE (@query)
With this query I want get col1 from SET and compare it to the column Region from Customer. I would like to get the matching CustomerKey for it.
After execution it says commands are executed successfully. But I want to save the result from @query in another table. I looked it up and most people say to use sp_executesql. I tried a few constructions as sampled and I would always get this error:
Msg 214, Level 16, State 2, Procedure sp_executesql, Line 12
Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'.
So the output should be a list of CustomerKeys in another table.
How can I save the results from EXECUTE into a variable? Then I assume I can INSERT INTO - SELECT in another table.
ThanksCREATE TABLE Customer
(CustomerKey INT , Name NVARCHAR(100));
GO
INSERT dbo.Customer
VALUES ( 1, N'Sam' )
GO
DECLARE @query nvarchar(max) = ''
declare @par varchar(10) = 'Name',
@key varchar(10) = 'Sam'
CREATE TABLE #temp ( CustomerKey INT );
SET @query =
insert #temp
SELECT CustomerKey
FROM Customer
where ' + @par + ' = '''+ @key+ ''' '
PRINT @query
EXEC sp_executesql @query
SELECT *
FROM #temp
DROP TABLE #temp;
DROP TABLE dbo.Customer
Cheers,
Saeid Hasani
Database Consultant
Please feel free to contact me at [email protected] as well as on Twitter and Facebook.
[My Writings on TechNet Wiki] [T-SQL Blog] [Curah!]
[Twitter] [Facebook] [Email] -
Exec stored procedure from another stored procedure - not working
Hey, we've got a bunch of .sql files that we run, and some of them are stored procedures. Our programs call the stored procedures from within the .sql files and that works, but we've tried calling a stored procedure from another stored procedure and it won't compile. The syntax looks the same, and we can run that second stored procedure from the SQL*Plus command prompt just fine, so we know it's in there. It doesn't matter whether we type exec or execute in the first stored procedure--it still gives us a compilation error. Here's the relevant bit of the code:
delete CMHISTORYINDEX;
commit;
exec SP_DAILY_TOTAL;
END SP_DAILY_CLOSING;
/Here's where we go into SQL*Plus and try to compile it:
Connected to:
Oracle Database 10g Enterprise Edition Release 10.1.0.3.0 - Production
With the Partitioning, Real Application Clusters, OLAP and Data Mining options
SQL> @sp_daily_closing.sql
Warning: Procedure created with compilation errors.
SQL> show errors
Errors for PROCEDURE SP_DAILY_CLOSING:
LINE/COL ERROR
34/7 PLS-00103: Encountered the symbol "SP_DAILY_TOTAL" when expecting
one of the following:
:= . ( @ % ;
The symbol ":=" was substituted for "SP_DAILY_TOTAL" to continue.
SQL>We've also tried changing SP_DAILY_CLOSING to lowercase, but it doesn't seem to help. As I mentioned before, we can type that same sort of thing in .sql files that are not stored procedures and the exec is compiled fine and runs correctly. What are we doing wrong?In the stored procedure remove "exec" :
delete CMHISTORYINDEX;
commit;
SP_DAILY_TOTAL;
END SP_DAILY_CLOSING; -
Running a SQL Stored Procedure from Power Query with Dynamic Parameters
Hi,
I want to execute a stored procedure from Power Query with dynamic parameters.
In normal process, query will look like below in Power Query. Here the value 'Dileep' is passed as a parameter value to SP.
Source = Sql.Database("ABC-PC", "SAMPLEDB", [Query="EXEC DBO.spGetData 'Dileep'"]
Now I want to pass the value dynamically taking from excel sheet. I can get the required excel cell value in a variable but unable to pass it to query.
Name_Parameter = Excel.CurrentWorkbook(){[Name="Table3"]}[Content],
Name_Value = Name_Parameter{0}[Value],
I have tried like below but it is not working.
Source = Sql.Database("ABC-PC", "SAMPLEDB", [Query="EXEC DBO.spGetData Name_Value"]
Can anyone please help me with this issue.
Thanks
DileepHi,
I got it. Below is the correct syntax.
Source = Sql.Database("ABC-PC", "SAMPLEDB", [Query="EXEC DBO.spGetData '" & Name_Value & "'"]
Thanks
Dileep -
SSRS - Stored procedure with Dynamic SQL Query
Am calling stored procedure in SSRS report. I have used Dynamic SQL query in stored procedure as I don't know the column name and column count. And I have used like below at end of the stored procedure "select * from ##temptable".
As I have used dynamic column, am not able to create report with this stored procedure. Can someone help me out to resolve this issue.
It will be highly appreciated if I get help.
ThanksI have tried everything. But nothing has worked out.
If I get solution for below issue, it would be highly appreciated.
"An error occurred during local report processing.
The definition of the repport 'Main Report' is invalid.
The report defintion is not valid. Details: The report definition has an invalid target namespace 'http://schemas.microsoft.com/sqlserver/reporting/2010/01/reportdefinition' which cannot be upgraded.
Thanks
Hello,
I would suggest you post the complete error message to us for further investigation, if you preview the report before you deploy you may get a more detailed error that will help diagnose the source of the problem.
This issue is more related to SQL Server Reporting Services, it's more appropriate to discuss it in the forum below:
https://social.technet.microsoft.com/Forums/sqlserver/en-US/home?forum=sqlreportingservices
Don't forget to elaborate your issue with more detail.
For the manual column, it might be the calculated field in SSRS. Here is the article for your reference, please see:
http://technet.microsoft.com/en-us/library/dd239322(v=sql.110).aspx
Regards,
Elvis Long
TechNet Community Support -
Build dynamic SQL query in Database Adapter.
Hi All,
I have a requirement to build dynamic sql query at Database Adapter.
My BPEL process is getting search spec as input from siebel. I need to process this searchspec in BPEL and need to build the SQL query dynamically at Database Adapter to fetch the records from DB.
it goes like this....
1. Sieble Search Spec: city1 OR city2 OR city3 OR city4 .....
I need to build query as
select * from S_ADDR_PER where city like 'city1' OR city like 'city2' OR city like 'city3' OR city like 'city4' ......
2. Siebel Search spec: city1 AND country1 AND state1....
I need to build query as
Select * from S_ADDR_PER where city like 'city1' AND country like 'country1' AND state like 'state1' ....
3. Siebel Search spec: state
I need to build query as
select * from S_ADDR_PER where state like '%state%';
Is it feasible in Database Adapter? if its Yes.
Any guidelines to achieve this?
Thank you
ChandraHi All,
I have a requirement to build dynamic sql query at Database Adapter.
My BPEL process is getting search spec as input from siebel. I need to process this searchspec in BPEL and need to build the SQL query dynamically at Database Adapter to fetch the records from DB.
it goes like this....
1. Sieble Search Spec: city1 OR city2 OR city3 OR city4 .....
I need to build query as
select * from S_ADDR_PER where city like 'city1' OR city like 'city2' OR city like 'city3' OR city like 'city4' ......
2. Siebel Search spec: city1 AND country1 AND state1....
I need to build query as
Select * from S_ADDR_PER where city like 'city1' AND country like 'country1' AND state like 'state1' ....
3. Siebel Search spec: state
I need to build query as
select * from S_ADDR_PER where state like '%state%';
Is it feasible in Database Adapter? if its Yes.
Any guidelines to achieve this?
Thank you
Chandra -
Best way to spool DYNAMIC SQL query to file from PL/SQL
Best way to spool DYNAMIC SQL query to file from PL/SQL [Package], not SqlPlus
I'm looking for suggestions on how to create an output file (fixed width and comma delimited) from a SELECT that is dynamically built. Basically, I've got some tables that are used to define the SELECT and to describe the output format. For instance, one table has the SELECT while another is used to defined the column "formats" (e.g., Column Order, Justification, FormatMask, Default value, min length, ...). The user has an app that they can use to customize the output...which leaving the gathering of the data untouched. I'm trying to keep this formatting and/or default logic out of the actual query. This lead me into a problem.
Example query :
SELECT CONTRACT_ID,PV_ID,START_DATE
FROM CONTRACT
WHERE CONTRACT_ID = <<value>>Customization Table:
CONTRACT_ID : 2,Numeric,Right
PV_ID : 1,Numeric,Mask(0000)
START_DATE : 3,Date,Mask(mm/dd/yyyy)The first value is the kicker (ColumnOrder) as well as the fact that the number of columns is dynamic. Technically, if I could use SqlPlus...then I could just use SPOOL. However, I'm not.
So basically, I'm trying to build a generic routine that can take a SQL string execute the SELECT and map the output using data from another table to a file.
Any suggestions?
Thanks,
JasonYou could build the select statement within PL/SQL and open it using a cursor variable. You could write it to a file using the package 'UTL_FILE'. If you want to display the output using SQL*Plus, you could have an out parameter as a ref cursor.
-
Hi,
How do I return two values from a
stored procedure into an "Execute SQL Task" please? Each of these two values need to be populated into an SSIS variable for later processing, e.g. StartDate and EndDate.
Thinking about stored procedure output parameters for example. Is there anything special I need to bear in mind to ensure that the SSIS variables are populated with the updated stored procedure output parameter values?
Something like ?
CREATE PROCEDURE [etl].[ConvertPeriodToStartAndEndDate]
@intPeriod INT,
@strPeriod_Length NVARCHAR(1),
@dtStart NVARCHAR(8) OUTPUT,
@dtEnd NVARCHAR(8) OUTPUT
AS
then within the SSIS component; -
Kind Regards,
Kieran.
Kieran Patrick Wood http://www.innovativebusinessintelligence.com http://uk.linkedin.com/in/kieranpatrickwood http://kieranwood.wordpress.com/Below execute statement should work along the parameter mapping which you have provided. Also try specifying the parameter size property as default.
Exec [etl].[ConvertPeriodToStartAndEndDate] ?,?,? output, ? output
Add a script task to check ssis variables values using,
Msgbox(Dts.Variables("User::strExtractStartDate").Value)
Do not forget to add the property "readOnlyVariables" as strExtractStartDate variable to check for only one variable.
Regards, RSingh -
How to send a Varying Array param to a PL/SQL Stored Procedure from Java
* I am VERY new to jdbc, and even somewhat new to Java
* I'm using Java 1.5, Oracle 10g.
* I need to call the following PL/SQL Stored Procedure from Java:
procedure setEventStatus
i_deQueueStatus in deQueueStatus_type
*deQueueStatus_type is the following (an array of deQueueStatus_OBJ):
CREATE OR REPLACE TYPE deQueueStatus_OBJ as object
eventID number (20),
dequeuestatus varchar2(20)
CREATE OR REPLACE TYPE deQueueStatus_TYPE IS VARYING ARRAY(500) of deQueueStatus_obj
*I have created a Java object as follows:
public class EventQueueDeQueueStatus
long eventID;
String dequeueStatus;
EventQueueDeQueueStatus(long eventID, String dequeueStatus)
this.eventID = eventID;
this.dequeueStatus = dequeueStatus;
I have an ArrayList of these.
I need to pass this list to the Stored Procedure. How do I create a java.sql.Array so I can call CallableStatement.setArray to set the parameter? Or do I use something else? I have tried setObject with both the ArrayList and also with a primitive array, but got "Invalid Column Type" both times.
Any help would be greatly appreciated. I just got this task today, and I have to make it work by Tuesday :-( !
Thanks,
KathyKathy,
Search the archives of this forum and the JDBC forum for the terms STRUCT and ARRAY and you can find some sample code on the JDBC How-To Documents page and the JDBC Samples which can both be accessed from this page:
http://www.oracle.com/technology/tech/java/sqlj_jdbc/index.html
Good Luck,
Avi. -
How to use @jws:sql call Stored Procedure from Workshop
Is there anyone know how to use @jws tag call Sybase stored procedure within
Workshop,
Thanks,Anurag,
Do you know is there any plan to add this feature in future release? and
when?
Thanks,
David
"Anurag Pareek" <[email protected]> wrote in message
news:[email protected]..
David,
In the current release, we do not support calling stored procedures from a
database control. You will have to write JDBC code in the JWS file to call
stored procedures.
Regards,
Anurag
Workshop Support
"David Yuan" <[email protected]> wrote in message
news:[email protected]..
Anurag,
I know how to use DB connection pool and create a db control with it. In
fact, we have created a Web Service with the db control using plain SQL
in
@jws:sql. However, my question here is how to use @jws tag in Weblogic
Workshop to create a Web Services based on Sybase stored procedure orany
Stored Proc not plain SQL.
Thanks,
David
"Anurag Pareek" <[email protected]> wrote in message
news:[email protected]..
David,
You can use a database control to obtain a connection from any JDBC
Connection Pool configured in the config.xml file. The JDBC Connectionpool
could be connecting to any database, the database control is
independent
of
that.
Regards,
Anurag
Workshop Support
"David Yuan" <[email protected]> wrote in message
news:[email protected]..
Is there anyone know how to use @jws tag call Sybase stored
procedure
within
Workshop,
Thanks, -
How to call PL-SQL script/stored procedure from Java?
Assume I want to call a PL-SQL stored procedure from external Java program.
How can I do this?
Is there a simple "Hello world" example for this?
PeterThis forum is for Oracle only not for java
Ug -
How to call PL-SQL script/stored procedure from BPEL?
Assume I want to call a PL-SQL stored procedure from BPEL.
How can I do this?
Is there a simple "Hello world" example for this?
PeterThe database adapter supports calling stored procedures. There is an example called "File2StoredProcedure" that you can use as a reference to get started.
-
Calling Oracle stored procedure from xMII Query Templates.
Hi All,
We have a requirement to call a Oracle stored procedure from xMII, the SP expects some inputs and then it returns multiple rows.
I tried different approches with no results, I remember some posts on the same topic but I could not get in search results.
Looking for some help in this regards
Rupesh.Hi Rupesh Bajaj,
In oracle stored procedure we have to use Packages..if you used packages the u have to assign to some variable.
To calling Stored procedure in Query Template is CALL Testing('[Param.1]','[Param.2]',,:X)
In above line Testing is Stored procedure name and Param.1 is parameters and X is Package.
Thanks
Ravilla Ramesh -
Calling stored procedure from embedded sql
I'm trying to call a stored procedure from embedded sql. I'm following the examples located in
http://download.oracle.com/docs/cd/B19306_01/appdev.102/a96109/pco06pls.htm#i9641
I have the following section in my .pco file before precompiling.
exec sql execute
begin
docs.grant_access_to_all_categories(:p_sam_id);
end;
end-exec.
When running procob on the file with the above code I get the following error.
Error at line 225, column 13 in file pco\docs_stored_procedures.pco
exec sql execute
............1
PCB-S-00576, PLS-201: identifier 'DOCS.GRANT_ACCESS_TO_ALL_CATEGORIES' must be d
eclared
Error at line 225, column 13 in file pco\docs_stored_procedures.pco
exec sql execute
............1
PCB-S-00576, PLS-0: Statement ignored
Any ideas on what I am doing wrong on calling this stored procedure.I get the same error when trying to precompile sample11.pco from the demo directory in the oracle client software.
Error at line 70, column 12 in file sample11.pco
EXEC SQL EXECUTE
...........1
PCB-S-00576, PLS-201: identifier 'EMP_DEMO_PKG.OPEN_CUR' must be declared
Error at line 70, column 12 in file sample11.pco
EXEC SQL EXECUTE
...........1
PCB-S-00576, PLS-0: Statement ignored
Maybe you are looking for
-
Hi, I understand that it's better if the home page links within my site resolve to my domain name rather than to domain name and the suffix /index.html. This can be achieved by specifying an absolute URL, but is there a better alternative method? Adv
-
Flow of Information from Quotation to Sales Order
Hi Group, Just want to understand is there any possibility to put a check while information is flowing from Quotation to Sales Order. Once information flows to Sales Order no one should be able to change the flown information in Sales Order. Any chan
-
Help quickly!!!!!
so i updated itunes and now it wont open. its saying there is an audio configuration problem. the thing is that i'm leaving for the airport in 2 hours and i need to update my ipod... so pls plss plssss help!!
-
Hi guys, I need to create an instance of the main class in my project. This main has the standard main method : public static void main (String args[]) ,which requires a character by command line. How to create an instance of this class from another
-
hi all, i want to stop the get pernr after some lines and want to run the remaining lines of the programm which is not in logical database. ITS URGENT..... Thx in advance Sunil