Lower case column names when using SELECT - mysql

I'm using the Kohana framework and I need to convert column names to lowercase. I don't have control of the db table structure. I want to do the following:
SELECT LOWER(*) FROM .....
but MYSQL does not like that. Whats the proper way of outputting the lower case column names if I don't know what the column names will be?

Found here http://dev.mysql.com/doc/refman/5.0/en/columns-table.html
SELECT LOWER(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'Table'
Below you can see both MSSQL and MySQL syntax for creating a dynamic query using the column results from the query above.
MSSQL Syntax
DECLARE #ColumnNames [nvarchar](1024)
SELECT #ColumnNames = COALESCE(#ColumnNames + ', ', '') + LOWER(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Table'
DECLARE #Sql [nvarchar](1024) = 'SELECT ' + #ColumnNames + ' FROM Table ' --Remember to put spaces after SELECT and before FROM
EXEC(#Sql)
With this you are dynamically building your query and then executing it.
MySQL Syntax
SELECT #ColumnNames := GROUP_CONCAT(LOWER(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Table';
SET #Sql = CONCAT('SELECT ', #ColumnNames, ' FROM Table ');
PREPARE stmt1 FROM #Sql;
EXECUTE stmt1;

Related

How to call MySQL function for every column that is present in table?

I need to call a mySQL function for all columns in a table.
I know how to do it for a particular column
Like this:
UPDATE `table_name` set `column_name` = function_name(`column_name`)
But i have no clue how to do it for all columns at once.
Thanks in advance.
Little clarification: I dont want to manually mention all columns, as i probably could have 200 columns table.
But i have no clue how to do it for all columns at once.
You just can't - there is no such shortcut in the update syntax.
You can do this with a single update statement, but you need to enumerate each and every column, like:
update table_name set
column_name1 = function_name(column_name1),
column_name2 = function_name(column_name2),
column_name3 = function_name(column_name3)
An alternative would be to use dynamic SQL to programatically generate the proper query string from catalog table information_schema.columns, and then execute it. This seems uterly complicated for what looks like a one-shot task... But here is sample code for that:
-- input variables
set #table_schema = 'myschema';
set #table_name = 'mytable';
set #function_name = 'myfunction';
-- in case "GROUP_CONCAT()" returns more than 1024 characters
set session group_concat_max_len = 100000;
-- build the "set" clause of the query string
select
#sql := group_concat(
'`', column_name, '` = ', #table_schema, '.', #function_name, '(`', column_name, '`)'
separator ', '
)
from information_schema.columns
where table_schema = #table_schema and table_name = #table_name;
-- entire query string
set #sql := concat('update ', #table_schema, '.', #table_name, ' set ', #sql);
-- debug
select #sql mysql;
-- execute for real
prepare stmt from #sql;
execute stmt;
deallocate prepare stmt;

how to get data from dynamic table in sql

How can I get data from chosen table of my database?
I'm going to work with database in c# application and I have the database includes that tables:
MyTable1;
MyTable2;
...
And I have tbl variable that is equal to tbl = "MyTable2";. I want to execute the code as following:select * from tbl
I try to execute this code:
SELECT *
FROM (
SELECT TABLE_NAME
FROM information_schema.tables
WHERE TABLE_NAME = 'MyTable1'
);
But the code returned error that Every derived table must have its own alias
I want to get all data from table whose name is equal to my variable (tbl) and its value can also be changed. How can I do it?
You might be able to do this using a prepared statement in MySQL:
SELECT TABLE_NAME
INTO #table
FROM information_schema.tables
WHERE TABLE_NAME = 'MyTable1';
SET #query = CONCAT('SELECT * FROM ', #table);
PREPARE stmt FROM #query;
EXECUTE stmt;
SELECT *
FROM (
SELECT TABLE_NAME
FROM information_schema.tables
WHERE TABLE_NAME = 'MyTable1'
) AS Blah
Try this:
DECLARE #SELECT nvarchar(500)
SET #SELECT = 'SELECT * FROM ' + #tbl
EXECUTE sp_executesql #SELECT

Truncate in multiple tables

I'm trying to create a way for me to apply truncate across multiple tables at the same time.
I tried the following code:
SELECT CONCAT('TRUNCATE TABLE ',table_schema,'.',TABLE_NAME, ';')
FROM INFORMATION_SCHEMA.TABLES
WHERE table_schema in ('mytable1','mytable2','mytable3');
More unsuccessfully, it is not truncating the tables.
Does anyone know of any way to do this?
DECLARE #CODE NVARCHAR(MAX) = '', #XML XML
SET #XML = STUFF((
SELECT ' ' + data.CODE_DELETE
FROM (
SELECT CONCAT ('TRUNCATE TABLE ', table_schema, '.', TABLE_NAME, '') AS CODE_DELETE
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME IN ('CITY', 'WORKERS')
) [data]
FOR XML PATH('')
), 1, 1, '')
SET #CODE = CAST(#XML AS VARCHAR(MAX))
SELECT #CODE
EXECUTE sp_executesql #CODE;
the variable #XML is to be able to convert the rows into a single value, then we must convert the sql code to varchar in order to execute it with
EXECUTE sp_executesql #CODE;
you can see the code that will be executed if you do this:
SELECT #CODE
city ​​and workers are tables that I have in my database, if you look I change table_schema by TABLE_NAME in the WHERE clause.
Please use transaction to do it if you want to keep it atomic.
START TRANSACTION;
// Your truncate statements;
COMMIT;

Mysql UNION with dynamic query

i have the following problem. I inherited a software that uses a database prefix for every customer.
All tables have the same structure and columns. For a data migration to new version i want to union all these tables
and set a customer foreign key instead and get rid of all the subtables. i'm looking for a way to create
a view for this task because i also want to stay backwards compatible for now.
I found this dynamic query which seems to do what i want
but i can't execute on my mysql server. I assume it was written for another sql server.
The table name structure is (about 80 customer tables):
customer1_faxe
customer2_faxe
customer3_faxe
customer4_faxe
...
How would you approach this problem?
DECLARE #SelectClause VARCHAR(100) = 'SELECT *'
,#Query VARCHAR(1000) = ''
SELECT #Query = #Query + #SelectClause + ' FROM ' + TABLE_NAME + ' UNION ALL '
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE '%_faxe'
SELECT #Query = LEFT(#Query, LEN(#Query) - LEN(' UNION ALL '))
EXEC (#Query)
This query is using SQL Server syntax. You need something like this:
declare #SelectClause varchar(8000);
declare #Query varchar(8000);
set #SelectClause = 'SELECT *';
SELECT #Query := group_concat(#SelectClause, ' FROM ', TABLE_NAME SEPARATOR ' UNION ALL ')
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE '%_faxe';
prepare stmt from #Query;
execute stmt;
Note that the group_concat() with separator simplifies the logic.

Mysql query search a string in all columns of a table

I wonder how I can mount a SQL as portable as possible to query for all columns of a table for a specific phrase, like:
Table
ID | Name | text | Date | Author | Status
1 | Augusto Weiand | Test text | 2010-01-01 | Deividi | 1
Query
SELECT *
FROM table
WHERE columns LIKE '%augusto%2010%text%"
I did not put enough detail, excuse me, I like to make a dynamic SQL, where I do not need to specify the columns with 'AND' or 'OR', as it is possible to do in Postgres:
Select *
From table
Where table::text ~~ '%augusto%2010%text%'
Here is how you would concatenate the values in dynamic SQL:
set #Pattern = '%augusto%';
select #q := concat('select * from Table1 ',
'where concat(', group_concat(column_name), ', "") like "', #Pattern, '"'
)
from information_schema.columns c
where table_name = 'Table1';
prepare st from #q;
execute st;
deallocate prepare st;
Of course, dynamic SQL is not particularly portable. The idea would work in most databases. The code would look different.
Tested and working here.
And finally, you can do this with variable substitution (which is the better approach):
select #q := concat('select * from Table1 ',
'where concat(', group_concat(column_name), ', "") like ?'
)
from information_schema.columns c
where table_name = 'Table1';
set #p = '%augusto%';
prepare st from #q;
execute st using #p;
deallocate prepare st;
Also tested (;-).
It's doable, although I strongly suggest you look into full-text search for efficiency;
To avoid looking for all patterns in all fields one by one, you can just concat and search in that;
SELECT *
FROM (SELECT id,CONCAT(name,'|',text,'|',date,'|',author,'|',status) txt
FROM Table1) a
WHERE txt LIKE '%augusto%'
AND txt LIKE '%2010%'
AND txt LIKE '%text%';
Note that no indexing will help you here, since you're searching in a calculated column. On the other hand, since you're searching with a leading wildcard %searchterm, you won't get much help from indexes even if searching field by field :)
An SQLfiddle to test with.
try this
Select * FROM table WHERE text LIKE "%text%"
OR date LIKE "%2010%"
OR Name LIKE "%augusto%"
if you want them all together then use AND
Select * FROM table WHERE text LIKE "%text%"
AND date LIKE "%2010%"
AND Name LIKE "%augusto%"
you can use this store procedure to search a text in all column in table
CREATE PROCEDURE dbo.sp_FindStringInTable #stringToFind VARCHAR(100),
#schema
sysname, #table sysname
AS
BEGIN TRY
DECLARE #sqlCommand varchar(max) = 'SELECT * FROM [' + #schema + '].[' +
#table + '] WHERE '
SELECT #sqlCommand = #sqlCommand + '[' + COLUMN_NAME + '] LIKE ''' +
#stringToFind + ''' OR '
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = #schema
AND TABLE_NAME = #table
AND DATA_TYPE IN ('char','nchar','ntext','nvarchar','text','varchar')
SET #sqlCommand = left(#sqlCommand,len(#sqlCommand)-3)
EXEC (#sqlCommand)
PRINT #sqlCommand
END TRY
BEGIN CATCH
PRINT 'There was an error. Check to make sure object exists.'
PRINT error_message()
END CATCH
Execute it like this
EXEC sp_FindStringInTable '%searchword%','schema_name', 'tablename'