tablename

Loop on tables with PL/pgSQL in Postgres 9.0+

只谈情不闲聊 提交于 2019-11-27 00:57:26
问题 I want to loop through all my tables to count rows in each of them. The following query gets me an error: DO $$ DECLARE tables CURSOR FOR SELECT tablename FROM pg_tables WHERE tablename NOT LIKE 'pg_%' ORDER BY tablename; tablename varchar(100); nbRow int; BEGIN FOR tablename IN tables LOOP EXECUTE 'SELECT count(*) FROM ' || tablename INTO nbRow; -- Do something with nbRow END LOOP; END$$; Errors: ERROR: syntax error at or near ")" LINE 1: SELECT count(*) FROM (sql_features) ^ QUERY: SELECT

How to select from MySQL where Table name is Variable

萝らか妹 提交于 2019-11-26 13:18:57
I have a case where getting the table name should be from a set variable like: SET @ID_1 = (SELECT ID FROM `slider` LIMIT 0,1); SET @Cat = (SELECT Category FROM `slider` LIMIT 0,1); select * from @Cat where ID = @ID_1 but doing that way MySQL outputs an error, so could someone show me how I can achieve that, because these are my baby steps in MySQL. You'd have to do this with a prepared statement . Something like: SET @s = CONCAT('select * from ', @Cat, ' where ID = ', @ID_1); PREPARE stmt1 FROM @s; EXECUTE stmt1; DEALLOCATE PREPARE stmt1; 来源: https://stackoverflow.com/questions/8809943/how-to

How to select from MySQL where Table name is Variable

萝らか妹 提交于 2019-11-26 03:40:02
问题 I have a case where getting the table name should be from a set variable like: SET @ID_1 = (SELECT ID FROM `slider` LIMIT 0,1); SET @Cat = (SELECT Category FROM `slider` LIMIT 0,1); select * from @Cat where ID = @ID_1 but doing that way MySQL outputs an error, so could someone show me how I can achieve that, because these are my baby steps in MySQL. 回答1: You'd have to do this with a prepared statement. Something like: SET @s = CONCAT('select * from ', @Cat, ' where ID = ', @ID_1); PREPARE

Table name as variable

假装没事ソ 提交于 2019-11-25 22:23:41
问题 I am trying to execute this query: declare @tablename varchar(50) set @tablename = \'test\' select * from @tablename This produces the following error: Msg 1087, Level 16, State 1, Line 5 Must declare the table variable \"@tablename\". What\'s the right way to have table name populated dynamically? 回答1: Table names and column names need to be static, if the query is static. For dynamic table or column names, you should generate the full SQL dynamically, and use sp_executesql to execute it.