Is it possible to write a variable after SELECT? - mysql

It is necessary to write a procedure that makes a request, which, in turn, should output all the objects of a particular column.
Here is what I tried:
CREATE PROCEDURE AttributeRequest(n CHAR(200))
begin
SELECT n FROM table;
end
But this variable is perceived as the name of the column itself and nothing comes out.
Tell me how to make such a request by the attribute of the object, please
I searched a bit, read the answers below, and I managed to implement this task in the following way:
CREATE PROCEDURE AttributeRequest(n CHAR(200))
begin
SET #t =CONCAT("SELECT ",n ," FROM table");
PREPARE e FROM #t;
EXECUTE e;
end

you will have to use dynamic sql for this
CREATE PROCEDURE AttributeRequest(#n CHAR(200)) AS
begin
declare #query varchar(1000);
set #query = 'select ['+#n+'] FROM table;
exec AttributeRequest #query
end
then you can excute it ,
exec AttributeRequest 'columnname'

Related

Is there a way to store in a variable the value returned from a prepared statement in a Stored Procedure in MySQL?

DELIMITER $$
CREATE PROCEDURE prepared_return_value(IN columnName varchar(20), IN tableName varchar(20), IN rowIndex varchar(10))
BEGIN
SET #columnName = '';
SET #columnName = CONCAT('Select distinct ',columnName ,' from ', tableName, ' LIMIT ', rowIndex, ',', '1', ';');
-- SELECT #columnName;
PREPARE stmt FROM #columnName;
EXECUTE stmt;
END $$
DELIMITER ;
So, i'm trying to dynamic pivoting a table using prepared statements to return the unique value of the rows and use it to alter a table.
But for that, i need to be able to store the returned row value, so i can use it in another prepared statement as the column name.
Apparently i can't store the value from the execution of prepared statement neither from a procedure.
I've tried lot of things by know, but none seemed to work, só... any hint on that?
The Varoable is session bound, so you can be used after the procedure has run .
SELECT #columnName
direct after the running outside if the procedure.
another option s to use an OUT Parameter besides the IN
Ypu would run
CALL return_value(columnName, tableName, rowIndex, #columnName)
And the crete procedure wil look like
CREATE PROCEDURE prepared_return_value(IN columnName varchar(20), IN tableName varchar(20), IN rowIndex varchar(10), OUT myoutput TEXT
Still what you are doing is highly problematic as it could be used for sql injection, so you should white list colu,nname an Tablename

T-SQL stored procedure result into variable

I have a stored procedure for some selection in JSON.
CREATE PROC [pr_MySP]
-- params
WITH ENCRYPTION
AS
BEGIN
SELECT
...
FOR JSON PATH;
END
And now I want to use this stored procedure in another.
CREATE PROC [pr_MySP_1]
-- params
WITH ENCRYPTION
AS
BEGIN
DECLARE #result_sp NVARCHAR(MAX);
EXEC #result_sp = [pr_MySP];
SELECT #result_sp;
END
But when I try SELECT #result_sp; it return 0.
What am I doing wrong?
I do not know what else you are doing within your first SP, but this might be better solved within an inlineable UDF:
CREATE FUNCTION dbo.CreateJSON()
RETURNS NVARCHAR(MAX)
AS
BEGIN
RETURN (SELECT TOP 10 * FROM sys.objects FOR JSON AUTO);
END
GO
--You can use the UDF in any context. You can define parameters to control the behaviour
DECLARE #TheJson NVARCHAR(MAX);
SET #TheJson=dbo.CreateJSON();
SELECT #TheJson;
GO
--Clean up
DROP FUNCTION dbo.CreateJSON;
In most cases an inline TVF is better in performance! But you'd have to join its resultset, which is not so intuitive...
You can store it in table variable instead.
DECLARE #result_sp (results NVARCHAR(MAX))
INSERT INTO #result_sp
EXEC [pr_MySP]
SELECT TOP 1 results FROM #result_sp
and if you still wanted it to store in a normal variable,
DECLARE #final NVARCHAR(MAX)
DECLARE #result_sp (results NVARCHAR(MAX))
INSERT INTO #result_sp
EXEC [pr_MySP]
SELECT TOP 1 #final = results FROM #result_sp
SELECT #final

How do I select every row from a table based on a string containing the name of the table?

In MySQL, I have a number of procedures which are more or less identical - they all perform the same (or very similar) operations, but they perform it on different tables.
I'd like to reduce these to one procedure, parameterized by table name, if possible. For example, suppose I wanted to execute a generic select:
SELECT * FROM TableFor("TableName")
Is this (or anything similar) possible in MySQL? Is it possible in any SQL dialect?
Per Tomva's Answer
A full example:
DROP PROCEDURE IF EXISTS example;
CREATE PROCEDURE example(IN tablename VARCHAR(1000)) BEGIN
SET #statement = CONCAT('SELECT * FROM ', #tablename);
PREPARE statement FROM #statement;
EXECUTE statement;
DEALLOCATE PREPARE statement;
END;
CALL example('tablename');
You can do this with a prepared statement.
It will be something along the lines of
SET #stat = CONCAT('SELECT * FROM ', #tab');
PREPARE stat1 FROM #stat;
EXECUTE stat1;
DEALLOCATE PREPARE stat1;
Dynamic SQL does not work in a function, so make a Stored Procedure from this, and you will be able to provide the table parameter.
I am going to assume you know what a stored procedure is (I hope you do otherwise my answer will be useless)
First create a table object in your procedure
declare #tablenames table(name varchar)
insert into #MonthsSale (name) values ('firsttable')
insert into #MonthsSale (name) values ('secondtable')
...
You can add this little line to suppress the rows affected messages:
SET NOCOUNT ON
Then create a cursor for this table and a variable to save your table name
DECLARE #TABLENAME VARCHAR
DECLARE tables_cursor CURSOR FOR SELECT name FROM #tablenames
Then loop through cursor and execute your code for each table name
OPEN Tables_cursor
FETCH NEXT FROM Tables_cursor INTO #Tablename
WHILE ##FETCH_STATUS = 0
BEGIN
YOUR CODE USING THE #Tablename
END
CLOSE Tables_cursor
DEALLOCATE Tables_cursor

Column name set in stored procedure but not working

Column name set in stored procedure but not working. But when I run this script empty rows appears. What I do this for run this script?
Create Procedure Test
()
AS
BEGIN
Declare #columnName nvarchar(50);
set #columnName ='StoreName';
SELECT *
FROM testtable
WHERE #columnName = 'storemanager'
END
You need to use dynamic SQL because you can't reference a column with a variable - T-SQL just doesn't parse things in that order. Try something like:
CREATE PROCEDURE dbo.Test
#columnName NVARCHAR(50),
#value NVARCHAR(4000)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql NVARCHAR(MAX);
SET #sql = N'SELECT * FROM dbo.testtable WHERE '
+ QUOTENAME(#columnName) + ' = #value;';
EXEC sp_executesql #sql, N'#value NVARCHAR(4000)', #value;
END
GO
QUOTENAME() wraps the column in [square brackets] and hopefully protects you from SQL injection. You should also read these posts:
Bad habits to kick : using SELECT * / omitting the column list
Bad habits to kick : avoiding the schema prefix
My stored procedure "best practices" checklist

Dynamic table names in stored procedure function

I've written a stored procedure function to get a name from a table. The trouble is that I want the table name to be passed in as a parameter (there are several different tables I need to use this function with):
DELIMITER $$
CREATE DEFINER=`root`#`localhost` FUNCTION `getName`(tableName VARCHAR(50), myId INT(11)) RETURNS VARCHAR(50)
begin
DECLARE myName VARCHAR(50);
SELECT
'name' INTO myName
FROM
tableName
WHERE
id=myId;
RETURN myName;
end
This method has an error because it uses the variable name "tableName" instead of the actual value of the variable.
I can work around this problem in a procedure by using a CONCAT like this:
SET #GetName = CONCAT("
SELECT
'name'
FROM
",tableName,"
WHERE
id=",myId,";
");
PREPARE stmt FROM #GetName;
EXECUTE stmt;
...but, when I try to do this in a function I get a message saying:
Dynamic SQL is not allowed in stored function or trigger
I tried to use a procedure instead, but I couldn't get it to just return a value, like a function does.
So, can anyone see a way to get around this problem. It seems incredibly basic really.
If you want to buld a SQL statement using identifiers, then you need to use prepared statements; but prepared statements cannot be used in functions. So, you can create a stored procedure with OUT parameter -
CREATE PROCEDURE getName
(IN tableName VARCHAR(50), IN myId INT(11), OUT myName VARCHAR(50))
BEGIN
SET #GetName =
CONCAT('SELECT name INTO #var1 FROM ', tableName, ' WHERE id=', myId);
PREPARE stmt FROM #GetName;
EXECUTE stmt;
SET myName = #var1;
END
Using example -
SET #tableName = 'tbl';
SET #myId = 1005;
SET #name = NULL;
CALL getName(#tableName, #myId, #name);
SELECT #name;