MySQL Stored Procedure dynamic change name of table - sql

I wanna change dynamicaly name of table in sql query. For example I have next stored procedure:
CREATE PROCEDURE NewProc(IN tableName varchar(64),IN message text)
BEGIN
INSERT INTO tableName VALUES (message);
END;
I need to change tableName in runtime, Can I to do it or not?
Thanks.

You must use dynamic SQL to prepare and execute an SQL string, to achieve what you describe.
Dynamic table names (or column names, or SQL keywords, etc.) must be interpolated into the SQL string before prepare. You can't use query parameters for these dynamic elements.
Be careful to avoid SQL injection vulnerabilities when you interpolate the table name into your SQL query. For example, you should check that the table name exists by looking it up in the information schema.
I agree with the comment from #OMG Ponies -- it's a code smell that you have multiple tables with identical structure such that you want to do the exact same insert to the exact same column. Code smells aren't a guarantee that you've got a bad design, but it's worth considering.

Related

Having trouble with SQL stored function syntax

I have this problem and I don't know what it means. As far as I understand you make a procedure inside a database so how do I write a procedure that specifies the database if it is different than the database I created the procedure in? I have asked and not received any clarification from my instructor about this. Here is the problem I am trying to solve:
Using SQL again, write a procedure that allows a user to specify a database, table, column in the table, and the new name of the index. This allows a user to add indexes without remembering the SQL syntax.
This is what I have so far come up with, but it doesn't seem to work. Or at least maybe I am writing the wrong thing in my query
CREATE DEFINER=`root`#`localhost` PROCEDURE `addindex`(
IN `db_name` VARCHAR(255),
IN `tbl_name` VARCHAR(255),
IN `col_name` VARCHAR(255),
IN `idx_name` VARCHAR(255)
)
BEGIN
CREATE INDEX idx_name ON db_name.tbl_name(col_name);
END
what I put in the query
addindex(nation, countries, AREA, index_area);
nation, countries, and area are the database, table, and column of a database I am using for testing this.
Tables, Database and Column names are identifiers and can't be variables.
What you can do in the body is use execute immediate like:
EXECUTE IMMEDIATE CONCAT('CREATE INDEX ',
idxname, ' on ', dbname, '.', tblname,
'(', col_name, ')')
Note this hasn't done table quoting. QUOTE() could be used around each of these identifiers.
Also consider compound multi-column indexes are useful and that stored procedures can't be written with a variable number of arguments. Hence quote(col_name) when multiple columns are passed will make it look like a single column.

How to get CREATE TABLE Statement from existing table in db2?

I am using DB2 and Oracle SQL Developer.
How to get the CREATE TABLE Statements from the existing tables?
There are too many tables and it will be a very lengthy process to do manually.
There is a special db2look utility for DDL extraction in Db2. You may refer to its options and their meaning at this link.
If you want SQL access to its capabilities, you may use the SYSPROC.DB2LK_GENERATE_DDL stored procedure supporting most of the utility's options. The routine has an output parameter getting "invocation number" int value after its call.
In case of a single table:
CALL SYSPROC.DB2LK_GENERATE_DDL ('-e -noview -t MY_SCHEMA.MY_TABLE', ?);
SELECT SQL_STMT
FROM SYSTOOLS.DB2LOOK_INFO_V
WHERE OP_TOKEN = <value_of_output_parameter_from_call_above>
ORDER BY OP_SEQUENCE;
In SQLDeveloper if you can see the table there's the initial Create Table Statement in the SQL Tab
You should do that for each table, this is a way to do it but I'm not sure it's fast enough for you.

How to use an IF statement within a view to drop/use a #Temp Table?

I need to create a view, which begins with the following SQL:
IF OBJECT_ID('tempdb..#TempTable') Is Not null
Drop Table #TempTable
I am also rebuilding this #TempTable further on in the view, and then using data in the Temptable for the rest of the query - for better performance. See:
Reduce cost for Table Valued Function - XML Reader in query plan - how?
However, SSMS is telling me:
Incorrect syntax near the keyword 'IF'
Views or functions are not allowed on temporary tables.
Table names that begin with '#' denote temporary tables.
Is there any way to use the IF statement, drop the Temptable, and then use the rebuilt Temptable in the view?
ANSWER - I need to use a stored procedure, not a view.
A stored procedure is quite different from a view. A view is simply an encapsulated query.
However, a stored procedure cannot be used in a SELECT statement. You can only execute it using EXEC.
What you probably want is a user-defined function (UDF). UDFs return a table, so they can be referenced in the FROM clause of a query. Unlike a view, they can contain multiple statements and can have parameters.
As a note, there is no need to delete temporary tables in stored procedures or functions. If the temporary table is declared in the body of the code, then it is automatically deleted when the code is exited. However, you might want to use a table variable instead.

SQL stored procedure

I have a table in sql in which I inserted my another table names.There are Table names column.So is it possible (programmatically inside SQL) getting the table names from this column and use them in Stored procedure as table name.How?inside SQL.
thanks
Sounds like something you will need to use dynamic SQL to do. Before you rush off to do this, I would recommend reading this article:
http://www.sommarskog.se/dynamic_sql.html

SQL SERVER table alias in stored proc

Is there a way to give an alias to a table which will then be referenced within a store procedure.
Declare #target= (sometalbewithveryverylonganduglyname)
Declare #source= (anothertablewithaveryuglyverylongverybadname)
Select * from #target
Insert into #target select from #source
delete from #source
Reason being, the table source and target could change (if the tablename is changed then we just change in one location), and for better readability.
In T-SQL you can't do:
Select * from #target
unless #target is defined as a table-variable, which requires you to set up the table as a user-defined type first. If you're attempting to assign the name of a physical table to the variable and access it this way you'd need to execute the statement using dynamic SQL.
exec ('Select * from #target')
If you just want to alias the table you could write your query like this:
Select * from sometalbewithveryverylonganduglyname AS t
From your question, sounds like the table name can change so you're going to need to use dynamic SQL in the end.
You can't do what you describe unless you resort to dynamic SQL as Yuck suggested, but doing that for the sake of not writing a long table name is not a valid justification. SSMS already includes intellisense and for SQL Server 2005 and below, you can use one of many of the free tools out there. That should reduce the amount of typing that you need to do as well as misspelling mistakes.
Besides, you can always do select t.column1 from really_long_and_ugly_name t ...
option 1) In that case you don't want to use a stored procedure, use some ORM library, it will allow you to switch between different table names with the same structure very easy
option 2) use views, that's what they are for, to hide underlying tables and allow those types of changes