This is very similar to question 653714, but for MySQL instead of SQL Server.
Basically, I have a complicated select that is the basis for several stored procedures. I would like to share the code across the stored procedures, however, I'm not sure how to do this. One way I could do this is by making the shared select a stored procedure and then calling that stored procedure from the other ones. I can't figure out how to work with the result set of the nested stored procedure. If I could put them in a temp table I could use the results effectively, but I can't figure out how to get them in a temp table. For example, this does not work:
CREATE TEMPORARY TABLE tmp EXEC nested_sp();
The problem is, Stored Procedures don't really return output directly. They can execute select statements inside the script, but have no return value.
MySQL calls stored procedures via CALL StoredProcedureName(); And you cannot direct that output to anything, as they don't return anything (unlike a function).
MySQL Call Command
You cannot "SELECT INTO" with stored procedures.
Create the temporary table first and have your stored procedure to store the query result into the created temporary table using normal "INSERT INTO". The temporary table is visible as long as you drop it or until the connection is closed.
i know this is coming really late but since it took me ages to find a real solution i might as well share. I worked on an example that is below.
the tables created are:
CREATE TABLE BOOK(
B_ID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(B_ID),
TITLE VARCHAR(100),
DESCRIPTION VARCHAR(30),
PRICE DOUBLE);
CREATE TABLE BOOK_COMMENT(
PRIMARY KEY(B_C_ID),
B_C_ID INT NOT NULL AUTO_INCREMENT,
REMARK VARCHAR(120),
B_ID INT,
FOREIGN KEY(B_ID) REFERENCES BOOK(B_ID));
CREATE TABLE AUTHOR(
A_ID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(A_ID),
A_NAME CHAR(15),
B_ID INT,
FOREIGN KEY(B_ID) REFERENCES BOOK(B_ID));
DELIMITER
CREATE PROCEDURE BOOK_IMPORTANT( _PRICE DOUBLE, _B_ID INT, A_NAME CHAR(15), _BD_ID INT)
BEGIN
INSERT INTO BOOK(PRICE)
VALUES(_PRICE);
SET _B_ID=LAST_INSERT_ID();
INSERT INTO BOOK_COMMENT(B_ID)
VALUES(_B_ID);
SET _BD_ID=LAST_INSERT_ID();
INSERT INTO AUTHOR(A_NAME,B_ID)
VALUES(A_NAME,_BD_ID);
END
then use the following to insert the values.
CALL BOOK_IMPORTANT('0.79',LAST_INSERT_ID(),'',LAST_INSERT_ID());
LAST_INSERT_ID() takes the last auto increment of the table and inserts it into the referencing column of the child table.
In the procedure parameters _B_ID and _BD_ID represent the B_ID since I need B_ID as a foreign key in both tables.
Sorry for the excess wording. All the other guys expect you to automatically know how to do it. Hope it helps
My first reaction was "That sounds like a view to me". Doesn't that abstract it enough so you can just add the variability into an SP per case?
Anything that adds a temp table that wouldn't otherwise be there is a very likely antipattern.
Maybe it's a closed topic, but I would like to offer a solution based on the properties of MySQL temporary tables. First, the way to create the temporary table would not be to call the stored procedure "CREATE TEMPORARY TABLE tmp EXEC nested_sp ();". The query is to the temporary table of "infrastructure", (to name it somehow).
To achieve the desired result, it is necessary to create 2 stored procedures, the first stored procedure processes the data and fills the temporary "infrastructure" table, the second stored procedure, reads this table and continues with the process and finally "DROP" the "infrastructure" table
This is the first stored procedure:
CREATE DEFINER = 'root'#'localhost'
PROCEDURE cajareal.priv_test()
BEGIN
CREATE TEMPORARY TABLE IF NOT EXISTS tmp(
column1 TEXT
, column2 TEXT
, column3 TEXT
);
INSERT INTO tmp(column1, column2 , column3) VALUES(CURDATE(), CURRENT_DATE(), CURRENT_TIMESTAMP());
END
This is the second stored procedure:
CREATE DEFINER = 'root'#'localhost'
PROCEDURE cajareal.priv_caller()
BEGIN
CALL priv_test;
-- Read data of "infrastructure" table
SELECT * FROM tmp;
-- Do the business logic
-- Delete the "infrastructure" table
DROP TABLE tmp;
END
I use this technique to analyze a string and convert it to the table
Related
I have a temp table used for intermediate calculation in a stored procedure.
Here is code segment:
CREATE TABLE #Updates
(
ID int not null,
ID2 int not null,
ID3 int not null
);
-- Do some operations and updates
IF OBJECT_ID('tempdb..#Updates','U') IS NOT NULL
DROP TABLE #Updates;
Since we are doing this a lot in a day. It causes SQL Server performance issue.
I want to change above code to
IF OBJECT_ID('tempdb..#Updates','U') IS NULL
BEGIN
CREATE TABLE #Updates
(
ID int not null,
ID2 int not null,
ID3 int not null
);
END
-- Do some operations and updates
IF OBJECT_ID('tempdb..#Updates','U') IS NOT NULL
DELETE FROM #Updates
I wonder if the new change will improve the SQL Server performance. If there is a better way to do this, please let me know, too.
Short version of answer
Remove the check for whether the temp table exists - these are only useful during development and manual execution of parts of the code
Unless you are deleting from the temp table then adding new data in, just let the temp table be removed naturally when the stored procedure finishes
Also consider whether a primary key and/or indexes will help
e.g., I've commented out stuff you don't need below and added a primary key on ID
-- IF OBJECT_ID('tempdb..#Updates','U') IS NULL
-- BEGIN
CREATE TABLE #Updates (
ID int not null PRIMARY KEY,
ID2 int not null,
ID3 int not null
);
-- END
<Do some operations and updates>
-- IF OBJECT_ID('tempdb..#Updates','U') IS NOT NULL
-- DELETE FROM #Updates
If, within that stored procedure, you
Create the temporary table
Insert values/data into it
Delete everything from it via DELETE FROM #Updates
Insert new values into it
then using TRUNCATE TABLE #Updates will be marginally faster that deleting from it.
Explanation/longer answer:
The temporary table is
only available during the current session/scope, and
deleted when the stored procedure finishes
If you run the stored procedure twice simultaneously, each will create, use, then delete its own temporary table - and they won't be able to be accessed by each other.
In terms of improving performance
If you are only using that table once (e.g., you create it, insert it, use it in a join, then are finished with it) you can instead move the SQL to be part of the join you are using (e.g., bypass the need to create a temp table). This avoids the cost of creating the temporary table, but may make your estimates in the new larger query worse, meaning poor performance
If you are using the table multiple times, you may consider putting indexes and/or a primary key on the temp table so it is sorted for those queries. Use columns that will be useful in joins with the other tables.
Temporary tables (e.g., in Temp_DB) are typically very fast. They also have some advantages over normal tables as they need much less transaction logging. I'd be surprised if the creation of a temporary table really affects time that much.
Pinal Dave does a very nice quick video about whether there is an effect of Dropping temporary tables in a stored procedure vs just letting them be removed automatically - in short the answer is 'no'.
UPDATE: I just did a test on an OK-ish computer that is about 10 years old now.
CREATE PROCEDURE _TestA AS BEGIN CREATE TABLE #a (a int); END;
GO
CREATE PROCEDURE _TestB AS BEGIN CREATE TABLE #a (a int); CREATE TABLE #b (a int); END;
GO
EXEC _TestA;
GO 1000
EXEC _TestB;
GO 1000
The first took 4 seconds, and the second took 6 seconds. This suggests that creating a temp table should only take a few milliseconds at most.
Assuming I have a table with one field called ID that stores 100 different integer values. I can select all of these rows simply by doing select id from example_table
I then have a stored procedure that I need to execute for each of these id's (as the sole parameter) and then select specific columns from (the stored procedure returns more data then I need). Besides executing the stored procedure 100 separate times into a temporary table and then selecting data from this table - how else could I do this?
You can pass table parameter to the procedure.
Check http://www.techrepublic.com/blog/datacenter/passing-table-valued-parameters-in-sql-server-2008/168
Update
CREATE TYPE LIST_OF_ID TABLE (ID INT);
go
CREATE PROCEDURE PROC1(#ids LIST_OF_ID READONLY)
....
I have to create a 10 stored procedure as follows:
In stored procedure # 1 I create temp table 1 and this temp table is used in stored procedure 2 to create another temp table and this new tem table is used in another STORED PROCEDURE and so on.
I am not sure how to create these stored procedure, because for these stored procedure I need to have temporary tables present in temdb.
Any help
Can you user Global Temporary Tables?
SELECT * INTO ##Users FROM UserTable
The Global temp tables will remain in tempdb until deleted and can be used across different stored procs.
Assuming you want to name the table (or some of its columns) that's about to be created based on the data present in the temp table, you might want to resort to dynamic SQL, since you can't use variables like this:
declare #foo varchar(50)
select #foo = tableName from #tempTable
create table #foo (fooColumn int)
But before you even think of using dynamic SQL, you've got to ask yourself whether you really need this solution.
what do Stored Procedures and Triggers in data base mean ?
how can i create Stored Procedures ?
how can i crest Triggers ?
if you have simple examples for each of these .please help :)
what i know is only about trigger which is activated if an action of(insert or delete or update ) violates the constrains specified but i don't know how to create ,so again if any have example please
Think of a Stored Procedure as a method in your code. It runs a specific set of instructions.
Stored Procedures are created to, for example, manage complex sets of data that would normally be a pain to handle along in your code.
You can create a Stored Procedure with the following instructions:
Oracle
CREATE OR REPLACE PROCEDURE P_PROCEDURE_NAME (
pParameter1 NUMBER
, pParameter2 VARCHAR2(100 Bytes)
) AS
BEGIN
-- Procedure code here...
END;
SQL Server
CREATE PROCEDURE cspProcedureName
#parameter1 int
, #parameter2 nvarchar(100)
AS
-- Procedure code here...
Oracle
As for the Triggers, they are sets of code called upon an action occuring to the related table. For instance, in Oracle, there are no INDENTITY columns such as SQL Server offers. Instead, Sequences are used along with Triggers to simulate the same. Hence, you will need to create an Oracle SEQUENCE, then the TRIGGER to update the ID field of your table.
CREATE SEQUENCE SEQ_CUSTOMERS
MINVALUE 1
MAXVALUE 65535
START WITH 1
INCREMENT BY 1;
CREATE OR REPLACE TRIGGER TRG_CUSTOMERS_INSERT
BEFORE INSERT
ON TBL_CUSTOMERS
FOR EACH ROW
BEGIN
:NEW.CUST_ID := SEQ_CUSTOMERS.NEXTVAL;
END;
SQL Server
A trigger example in SQL Server would be updating automatically the update datetime of a record. Consider the following:
CREATE TABLE Customers (
CustId int NOT NULL IDENTITY(1, 1) PRIMARY KEY
, CustName nvarchar(100) NOT NULL
, CreatedOn datetime DEFAULT GETDATE()
, LastUpdate datetime NOT NULL
)
GO
CREATE TRIGGER trgCustomersUpdt
AFTER UPDATE
ON Customers
AS
update Customers
set LastUpdate = GETDATE()
where CustId = inserted.Custid
GO
DISCLAIMER
This code has not been tested and may require minor changes for it to work properly against its respective RDBMS.
To sum it up, Triggers are mainly used to as illustrated here, despite there are many other possible use, such as building up an history of table changes that occured throught time, keeping all records of transactions into an history table or the like. The Stored Procedures are mainly used to perform complex database tasks where this would get too complex to do in code.
like i declared a table...
declare #tempTable TABLE
(Id bigint identity(1,1),
bKey int,
DateT DateTime,
Addres nvarchar(max),
unit bigint)
and i want to drop it...but im stucked coz drop table n truncate are not working.
ani ideaaa...???
Table variables only live while they are in scope, in your case for the duration of the stored procedure. It will delete itself once the procedure completes.
You might be thinking of a temporary table:
CREATE TABLE #MyTempTable
There are differences between temporary tables and table variables:
http://sqlnerd.blogspot.com/2005/09/temp-tables-vs-table-variables.html
A better link:
http://www.sql-server-performance.com/articles/per/temp_tables_vs_variables_p1.aspx
You don't need to drop table variables (i.e. those that start with #)
You've declared the table as a table variable. It will only exist for the duration of the stored procedure. When the procedure ends, it is automatically "dropped" (ceases to exist is more accurate, as it never really existed in the way other tables do). You cannot drop them manually.
You created a temporary table which is saved in a variable. It only exists as long as the store procedure is being executed. When the SP has finished the temporary table ceases to exists and it's being deleted automatically.
edit:
you could try testing it by running the stored procedure and then try to run a select query on your #tempTable
why do you want to drop a table variable? scope of table variable is in declare stored procedure only...
check this article... Table Variables In T-SQL
UPDATE
Use #temptable as suggested by #Adam...
Then TRUNCATE TABLE #temptable, instead of DROP TABLE; this way no need to recreate it within loop.
In your SP, this will remove all the values from your declared table
DELETE FROM #tempTable