I have one procedure in my MySQL Database.
My procedure working fine. But currently I have to set order by tblUserKeyStatus.createdDate inside IF (opt=1) condition and when I set order by, It gives me the following error
Error Code: 1054. Unknown column 'tblUserKeyStatus.createdDate' in 'order clause
My Stored Procedure is given below
CREATE PROCEDURE proc_GetStatus(IN _userId varchar(64) , IN _qtr int, IN opt int)
BEGIN
IF (opt = 1) then
SELECT tblKeyStatus.*,'pending' AS `Status`,'' as scheduleDate,
' ' as doneDate,' ' as result FROM tblUserKeyStatus,tblKeyStatus WHERE tblKeyStatus.trimId not in
(SELECT trimId from tblUserKeyStatus WHERE userId=_userId)
union
SELECT tblKeyStatus.*,tblUserKeyStatus.`Status` AS `Status`,tblUserKeyStatus.scheduleDate,
tblUserKeyStatus.doneDate,tblUserKeyStatus.result FROM tblKeyStatus,tblUserKeyStatus WHERE
tblUserKeyStatus.trimId=tblKeyStatus.trimId and tblUserKeyStatus.userId=_userId
order by tblUserKeyStatus.createdDate;
Else
SELECT * from tblKeyStatus WHERE qtr=_qtr;
End if;
END
ORDER BY is applied to the whole query specified in the UNION operation, so that the entire result set returned by UNION is ordered.
Try to select createdDate field in both subqueries, so that it is accessible to ORDER BY:
SELECT tblUserKeyStatus.createdDate,
tblKeyStatus.*,'pending' AS `Status`,
'' as scheduleDate,
' ' as doneDate,
' ' as result
FROM tblUserKeyStatus, tblKeyStatus
WHERE tblKeyStatus.trimId not in (SELECT trimId
from tblUserKeyStatus
WHERE userId=_userId)
UNION
SELECT tblUserKeyStatus.createdDate,
tblKeyStatus.*,
tblUserKeyStatus.`Status` AS `Status`,
tblUserKeyStatus.scheduleDate,
tblUserKeyStatus.doneDate,tblUserKeyStatus.result
FROM tblKeyStatus,tblUserKeyStatus
WHERE tblUserKeyStatus.trimId=tblKeyStatus.trimId and
tblUserKeyStatus.userId=_userId
ORDER BY createdDate;
You also have to remove the tblUserKeyStatus name prefix.
Try having braces for select
CREATE PROCEDURE proc_GetStatus(IN _userId varchar(64) , IN _qtr int, IN opt int)
BEGIN
IF (opt = 1) then
SELECT tblKeyStatus.*,'pending' AS `Status`,'' as scheduleDate,
' ' as doneDate,' ' as result FROM tblUserKeyStatus,tblKeyStatus WHERE tblKeyStatus.trimId not in
((SELECT trimId from tblUserKeyStatus WHERE userId=_userId)
union
(SELECT tblKeyStatus.*,tblUserKeyStatus.`Status` AS `Status`,tblUserKeyStatus.scheduleDate,
tblUserKeyStatus.doneDate,tblUserKeyStatus.result FROM tblKeyStatus,tblUserKeyStatus WHERE
tblUserKeyStatus.trimId=tblKeyStatus.trimId and tblUserKeyStatus.userId=_userId
order by createdDate));
Else
SELECT * from tblKeyStatus WHERE qtr=_qtr;
End if;
END
Related
I have a Stored Procedure that takes three parameters, one of which is TEXT and it should contain comma separated values with ids, something like this -> '12345,54321,11111,22222', and this it inserts a row with data for each id in the list. Below is the Stored Procedure:
DELIMITER //
-- Create Stored Procedure
CREATE PROCEDURE MyProcedure(
IN ItemUUID VARCHAR(255),
IN ReceiverIds TEXT,
IN ItemCreated VARCHAR(255)
)
BEGIN
DECLARE strLen INT DEFAULT 0;
DECLARE SubStrLen INT DEFAULT 0;
IF ReceiverIds IS NULL THEN
SET ReceiverIds = '';
END IF;
do_this:
LOOP
SET strLen = LENGTH(ReceiverIds);
INSERT INTO item_receiver (item_uuid, receiver_id, item_created)
VALUES (ItemUUID ,SUBSTRING_INDEX(ReceiverIds, ',', 1),ItemCreated);
SET SubStrLen = LENGTH(SUBSTRING_INDEX(ReceiverIds, ',', 1)) + 2;
SET ReceiverIds = MID(ReceiverIds, SubStrLen, strLen);
IF ReceiverIds = '' THEN
LEAVE do_this;
END IF;
END LOOP do_this;
END//
DELIMITER ;
To get comma separated values with ids, something like this -> '12345,54321,11111,22222' I execute subquery, however, when I call this Stored Procedure I get this error -> Error Code: 1242. Subquery returns more than 1 row
SET group_concat_max_len = 2048;
call MyProcedure('random_test_uuid',(
SELECT CAST(GROUP_CONCAT(receiver_id SEPARATOR ',') AS CHAR) AS receiver_ids FROM receiver
WHERE user_id LIKE (SELECT user_id FROM user WHERE user_name LIKE 'myName')
GROUP BY receiver_id ),
'2017-09-24 23:44:32');
The problem is the subquery. Remove the group by:
SELECT CAST(GROUP_CONCAT(receiver_id SEPARATOR ',') AS CHAR) AS receiver_ids
FROM receiver
WHERE user_id LIKE (SELECT user_id FROM user WHERE user_name LIKE 'myName')
With the group by, you are getting a separate row for each receiver_id. The group_concat() is not doing anything.
Also, the CAST() is unnecessary. And this would typically be written as:
SELECT GROUP_CONCAT(r.receiver_id SEPARATOR ',') AS receiver_ids
FROM receiver r JOIN
user u
ON u.user_id = r.user_id
WHERE u.user_name LIKE 'myName';
If 'myName' is not using wildcards, then = is more appropriate than like.
If receiver_id is not unique in receiver, then you might want to add distinct to the group_concat().
I am making a C# project in which I need help to generate and insert fields like below on MySQL database.
161013001
Where:
16 is Year,
10 is Month,
13 is day
and 001 is auto-increment numbers that reset each days.
Eg.
161012-001
161012-002
161012-002
161013-001
161013-002
161014-001
161014-002
161014-003
161014-004
161014-005
161015-001
please guide me how to make this that ID reset each day and start from 1 after every day.
Here both MySQL & SQL Server Implementation are added,
MySQL:
DROP TEMPORARY TABLE TempDate;
CREATE TEMPORARY TABLE TempDate(
Id VARCHAR(50),
Comments VARCHAR(50)
);
INSERT INTO TempDate(Id,Comments)
SELECT '190630-001', '1'
UNION
SELECT '190630-002', '2'
UNION
SELECT '190701-001', '1'
UNION
SELECT '190701-002', '2'
UNION
SELECT '190701-003', '3';
SET #v_ToDay = '';
SET #v_ToDay = (SELECT date_format(current_date(),'%y%m%d'));
SET #v_TotalByDay = '' ;
SET #v_TotalByDay =(
SELECT CONCAT('000',CAST(CASE WHEN COUNT(1) = 0 THEN 1 ELSE COUNT(1)+1 END as CHAR))
FROM TempDate
WHERE LEFT(Id,6) = #v_ToDay);
SELECT CONCAT(#v_ToDay, '-', CASE WHEN CHAR_LENGTH(RTRIM(#v_TotalByDay)) > 3 THEN RIGHT(#v_TotalByDay,3) ELSE #v_TotalByDay END) as NewIdColumn
SQL Server:
DECLARE #TempDate TABLE(
Id NVARCHAR(50),
Comments NVARCHAR(MAX)
)
INSERT INTO #TempDate(Id,Comments)
SELECT '190630-001', '1'
UNION
SELECT '190630-002', '2'
UNION
SELECT '190701-001', '1'
UNION
SELECT '190701-002', '2'
UNION
SELECT '190701-003', '3'
DECLARE #ToDay NVARCHAR(20) = (SELECT CONVERT(NVARCHAR(6), GETDATE(), 12))
DECLARE #TotalByDay NVARCHAR(20) = ''
SELECT #TotalByDay = '000' + CAST(CASE WHEN COUNT(1) = 0 THEN 1 ELSE COUNT(1)+1 END as NVARCHAR(20) )
FROM #TempDate
WHERE LEFT(Id,6) = #ToDay
SELECT #ToDay + '-' + CASE WHEN LEN(#TotalByDay) > 3 THEN RIGHT(#TotalByDay,3) ELSE #TotalByDay END as NewIdColumn
my situation is little more different then this question ....
i have a legacy database (it's not operational only use for reporting
purpose..)
in this DB transaction table was a auto increment tranx id column.
like 1, 2, 3 ...... but now our new report need meaningful tranx id
(yyMMDD<count of that day>) like this question. so actually i need a
select query to solve this problem.
with the help of #Khairul 's logic i solve my problem ....
i share my solution for other's help....
SELECT
trnx_id, account_id, pay_amount,counter_id, trantime, trandate
FROM(
SELECT
#id:=IF(#prev != t.trandate, #rownum:=1, #rownum:=#rownum+1)
,#prev:=t.trandate
,CONCAT(
SUBSTR(YEAR(t.`trandate`),3) -- year
,IF(LENGTH(MONTH(t.`trandate`))=1,CONCAT('0',MONTH(t.`trandate`)),MONTH(t.`trandate`)) -- month
,IF(LENGTH(DAY(t.`trandate`))=1,CONCAT('0',DAY(t.`trandate`)),DAY(t.`trandate`)) -- day
,IF(LENGTH(#id)=1,CONCAT('000',#id),IF(LENGTH(#id)=2,CONCAT('00',#id),IF(LENGTH(#id)=3,CONCAT('0',#id),#id))) -- count
) AS trnx_id
,t.*
FROM tax_info t ORDER BY t.`trandate`, t.`trantime`
) AS te
and my query result is ..........
After solving my problem i try to solve this question .......
for this i use a trigger for input auto increment custom column ...
my code is below , here my payment column has a custom tranx id ....
DELIMITER $$
DROP TRIGGER tranxidGeneration$$
CREATE
TRIGGER tranxidGeneration BEFORE INSERT ON payment
FOR EACH ROW BEGIN
DECLARE v_tranx_id_on INT;
-- count total row of that day
select IFNULL(COUNT(tranx_id),0)+1 Into v_tranx_id_on from payment where SUBSTR(tranx_id,1,6) = DATE_FORMAT(NOW(), "%y%m%d");
-- set custom generate id into tranx_id column
SET NEW.tranx_id := CONCAT(DATE_FORMAT(NOW(), "%y%m%d"),LPAD(v_tranx_id_on,4,0)) ;
END;
$$
DELIMITER ;
Is there any SQL lingo to return JUST the first two columns of a table WITHOUT knowing the field names?
Something like
SELECT Column(1), Column(2) FROM Table_Name
Or do I have to go the long way around and find out the column names first? How would I do that?
You have to get the column names first. Most platforms support this:
select column_name,ordinal_position
from information_schema.columns
where table_schema = ...
and table_name = ...
and ordinal_position <= 2
There it´s
declare #select varchar(max)
set #select = 'select '
select #select=#select+COLUMN_NAME+','
from information_schema.columns
where table_name = 'TABLE' and ordinal_position <= 2
set #select=LEFT(#select,LEN(#select)-1)+' from TABLE'
exec(#select)
A dynamic query using for xml path will also do the job:
declare #sql varchar(max)
set #sql = (SELECT top 2 COLUMN_NAME + ',' from information_schema.columns where table_name = 'YOUR_TABLE_NAME_HERE' order by ordinal_position for xml path(''))
set #sql = (SELECT replace(#sql +' ',', ',''))
exec('SELECT ' + #sql + ' from YOUR_TABLE_NAME_HERE')
I wrote a stored procedure a while back to do this exact job. Even though in relational theory there is no technical column order SSMS is not completely relational. The system stores the order in which the columns were inserted and assigns an ID to them. This order is followed using the typical SELECT * statement which is why your SELECT statements appear to return the same order each time. In practice its never a good idea to SELECT * with anything as it doesn't lock the result order in terms of columns or rows. That said I think people get so stuck on 'you shouldn't do this' that they don't write scripts that actually can do it. Fact is there is predictable system behavior so why not use it if the task isn't super important.
This SPROC of course has caveats and is written in T-SQL but if your looking to just return all of the values with the same behavior of SELECT * then this should do the job pretty easy for you. Put in your table name, the amount of columns, and hit F5. It returns them in order from left to right the same as you'd be expecting. I limited it to only 5 columns but you can edit the logic if you need any more. Takes both temp and permanent tables.
EXEC OnlySomeColumns 'MyTable', 3
/*------------------------------------------------------------------------------------------------------------------
Document Title: The Unknown SELECT SPROC.sql
Created By: CR
Date: 4.28.2013
Purpose: Returns all results from temp or permanent table when not knowing the column names
SPROC Input Example: EXEC OnlySomeColumns 'MyTable', 3
--------------------------------------------------------------------------------------------------------------------*/
IF OBJECT_ID ('OnlySomeColumns', 'P') IS NOT NULL
DROP PROCEDURE OnlySomeColumns;
GO
CREATE PROCEDURE OnlySomeColumns
#TableName VARCHAR (1000),
#TotalColumns INT
AS
DECLARE #Column1 VARCHAR (1000),
#Column2 VARCHAR (1000),
#Column3 VARCHAR (1000),
#Column4 VARCHAR (1000),
#Column5 VARCHAR (1000),
#SQL VARCHAR (1000),
#TempTable VARCHAR (1000),
#PermanentTable VARCHAR (1000),
#ColumnNamesAll VARCHAR (1000)
--First determine if this is a temp table or permanent table
IF #TableName LIKE '%#%' BEGIN SET #TempTable = #TableName END --If a temporary table
IF #TableName NOT LIKE '%#%' BEGIN SET #PermanentTable = #TableName END --If a permanent column name
SET NOCOUNT ON
--Start with a few simple error checks
IF ( #TempTable = 'NULL' AND #PermanentTable = 'NULL' )
BEGIN
RAISERROR ( 'ERROR: Please select a TempTable or Permanent Table.',16,1 )
END
IF ( #TempTable <> 'NULL' AND #PermanentTable <> 'NULL' )
BEGIN
RAISERROR ( 'ERROR: Only one table can be selected at a time. Please adjust your table selection.',16,1 )
END
IF ( #TotalColumns IS NULL )
BEGIN
RAISERROR ( 'ERROR: Please select a value for #TotalColumns.',16,1 )
END
--Temp table to gather the names of the columns
IF Object_id('tempdb..#TempName') IS NOT NULL DROP TABLE #TempName
CREATE TABLE #TempName ( ID INT, Name VARCHAR (1000) )
--Select the column order from a temp table
IF #TempTable <> 'NULL'
BEGIN
--Verify the temp table exists
IF NOT EXISTS ( SELECT 1
FROM tempdb.sys.columns
WHERE object_id = object_id ('tempdb..' + #TempTable +'') )
BEGIN
RAISERROR ( 'ERROR: Your TempTable does not exist - Please select a valid TempTable.',16,1 )
RETURN
END
SET #SQL = 'INSERT INTO #TempName
SELECT column_id AS ID, Name
FROM tempdb.sys.columns
WHERE object_id = object_id (''tempdb..' + #TempTable +''')
ORDER BY column_id'
EXEC (#SQL)
END
--From a permanent table
IF #PermanentTable <> 'NULL'
BEGIN
--Verify the temp table exists
IF NOT EXISTS ( SELECT 1
FROM syscolumns
WHERE id = ( SELECT id
FROM sysobjects
WHERE Name = '' + #PermanentTable + '' ) )
BEGIN
RAISERROR ( 'ERROR: Your Table does not exist - Please select a valid Table.',16,1 )
RETURN
END
SET #SQL = 'INSERT INTO #TempName
SELECT colorder AS ID, Name
FROM syscolumns
WHERE id = ( SELECT id
FROM sysobjects
WHERE Name = ''' + #PermanentTable + ''' )
ORDER BY colorder'
EXEC (#SQL)
END
--Set the names of the columns
IF #TotalColumns >= 1 BEGIN SET #Column1 = (SELECT Name FROM #TempName WHERE ID = 1) END
IF #TotalColumns >= 2 BEGIN SET #Column2 = (SELECT Name FROM #TempName WHERE ID = 2) END
IF #TotalColumns >= 3 BEGIN SET #Column3 = (SELECT Name FROM #TempName WHERE ID = 3) END
IF #TotalColumns >= 4 BEGIN SET #Column4 = (SELECT Name FROM #TempName WHERE ID = 4) END
IF #TotalColumns >= 5 BEGIN SET #Column5 = (SELECT Name FROM #TempName WHERE ID = 5) END
--Create a select list of only the column names you want
IF Object_id('tempdb..#FinalNames') IS NOT NULL DROP TABLE #FinalNames
CREATE TABLE #FinalNames ( ID INT, Name VARCHAR (1000) )
INSERT #FinalNames
SELECT '1' AS ID, #Column1 AS Name UNION ALL
SELECT '2' AS ID, #Column2 AS Name UNION ALL
SELECT '3' AS ID, #Column3 AS Name UNION ALL
SELECT '4' AS ID, #Column4 AS Name UNION ALL
SELECT '5' AS ID, #Column5 AS Name
--Comma Delimite the names to insert into a select statement. Bracket the names in case there are spaces
SELECT #ColumnNamesAll = COALESCE(#ColumnNamesAll + '], [' ,'[') + Name
FROM #FinalNames
WHERE Name IS NOT NULL
ORDER BY ID
--Add an extra bracket at the end to complete the string
SELECT #ColumnNamesAll = #ColumnNamesAll + ']'
--Tell the user if they selected to many columns
IF ( #TotalColumns > 5 AND EXISTS (SELECT 1 FROM #FinalNames WHERE Name IS NOT NULL) )
BEGIN
SELECT 'This script has been designed for up to 5 columns' AS ERROR
UNION ALL
SELECT 'Only the first 5 columns have been selected' AS ERROR
END
IF Object_id('tempdb..#FinalNames') IS NOT NULL DROP TABLE ##OutputTable
--Select results using only the Columns you wanted
IF #TempTable <> 'NULL'
BEGIN
SET #SQL = 'SELECT ' + #ColumnNamesAll + '
INTO ##OutputTable
FROM ' + #TempTable + '
ORDER BY 1'
EXEC (#SQL)
END
IF #PermanentTable <> 'NULL'
BEGIN
SET #SQL = 'SELECT ' + #ColumnNamesAll + '
INTO ##OutputTable
FROM ' + #PermanentTable + '
ORDER BY 1'
EXEC (#SQL)
END
SELECT *
FROM ##OutputTable
SET NOCOUNT OFF
SQL doesn't understand the order of columns. You need to know the column names to get them.
You can look into querying the information_schema to get the column names. For example:
SELECT column_name
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tbl_name'
ORDER BY ordinal_position
LIMIT 2;
You can query the sysobject of the table to find out the first two column then dynamically generate the SQL statement you need.
If you want a permant object that you can query over and over again make a view for each table that only returns the first 2 columns. You can name the columns Column1 and Column2 or use the existing names.
If you want to return the first two columns from any table without any preprocessing steps create a stored procedure that queries the system information and executes a dynamic query that return the first two columns from the table.
Or do I have to go the long way around and find out the column names first? How would I do that?
It's pretty easy to do manually.
Just run this first
select * from tbl where 1=0
This statement works on all major DBMS without needing any system catalogs.
That gives you all the column names, then all you need to do is type the first two
select colname1, colnum2 from tbl
SELECT IF((
SELECT COUNT(TABLE_NAME)
FROM information_schema.tables
WHERE TABLE_SCHEMA='database0' AND TABLE_NAME='table'
) >0 , (
SELECT id
FROM database1.table
WHERE id NOT IN (SELECT id FROM database0.table)
), NULL) AS pk_value;
The table database0.table may not exist; if the table does not exist, I want to skip the true clause of the IF statement. Even when the IF statement should return NULL, I get the error that database0.table does not exist. What can I do so that the query returns NULL instead of throwing an error if the table does not exist?
As mentioned in comments, queries are error-checked before they are run, so referring to a non-existent table won't work. You can store it as a function, which is only evaluated at run-time:
DROP FUNCTION IF EXISTS get_pk;
DELIMITER //
CREATE FUNCTION get_pk()
RETURNS INT
BEGIN
DECLARE counter INT;
DECLARE pk_value INT;
SELECT COUNT(table_name) INTO counter
FROM information_schema.tables
WHERE table_schema = 'database0' AND table_name = 'table';
IF counter = 1 THEN
SELECT id INTO pk_value
FROM database1.table
WHERE id NOT IN (SELECT id FROM database0.table);
ELSE
SELECT NULL INTO pk_value;
END IF;
RETURN pk_value;
END//
DELIMITER ;
Then access the value like this:
SELECT get_pk();
I'm creating a stored procedure into which i'm passing an "order" dynamically like so:
CREATE PROCEDURE `getStuff`(IN orderSQL VARCHAR(100))
BEGIN
SELECT id, name, createdate
FROM mytable
ORDER BY
CASE WHEN orderSQL='id_desc' THEN CONCAT(id, '') END DESC,
CASE WHEN orderSQL='id_asc' THEN CONCAT(id, '') END ASC,
CASE WHEN orderSQL='name_desc' THEN name END DESC,
CASE WHEN orderSQL='name_asc' THEN name END ASC,
CASE WHEN orderSQL='date_desc' THEN CONCAT(createdate, '') END DESC,
CASE WHEN orderSQL='date_asc' THEN CONCAT(createdate, '') END ASC
END
As you can see i'm converting all the non VARCHAR fields to VARCHAR using CONCAT, because mixing possible order types doesn't work as explained here https://web.archive.org/web/20211029044050/https://www.4guysfromrolla.com/webtech/010704-1.shtml.
My issue is that now ordering by name works, but non string orders come back as 1,10,11,2,3,4,5,6,7,8,9. etc
Is there a way to use mixed datatype dynamic ordering, and still return in the correct order for ints, datetimes etc.
The solution is to create the SQL statement full dynamically like so
DELIMITER $$
CREATE PROCEDURE GetStuff (IN orderSQL varchar(100) )
BEGIN
DECLARE SQLStatement varchar(255);
-- Enter the dynamic SQL statement into the
-- variable #SQLStatement
SET SQLStatement = CONCAT('SELECT id, name, createdate ',
'FROM mytable ',
'ORDER BY ',orderSQL);
PREPARE stmt FROM SQLStatement;
EXECUTE stmt;
END $$
DELIMITER ;
See here for more info: http://rpbouman.blogspot.com/2005/11/mysql-5-prepared-statement-syntax-and.html
You should use prepared statements to build and execute custom query or you should write big CASE condition with all your queries, i.e. -
CASE orderSQL
WHEN 'id_desc' THEN
SELECT id, name, createdate FROM mytable ORDER BY id;
WHEN 'id_desc' THEN
SELECT id, name, createdate FROM mytable ORDER BY id_desc;
...
...
...
END CASE;