How to use cursors to extract data from multiple tables
P粉141035089
2023-08-16 13:12:27
<p>I have a query that returns multiple tables, something like this: </p>
<pre class="brush:php;toolbar:false;">SELECT TableName, DatabaseName '.' TableName, ColumnName
FROM DBC.Columns
WHERE ColumnName = 'id'</pre>
<p>I need to loop through these tables by looking at the information stored in them in order to get only specific tables. </p>
<p>I tried the code below, using 'LOOP' and a cursor, but it says <code>Invalid query</code> (code comes from here): </p>
<pre class="brush:php;toolbar:false;">DECLARE cursor_Tables CURSOR FOR
SELECT DatabaseName || '.' || TableName
FROM DBC.Columns
WHERE ColumnName ='id';
OPEN cursor_Tables;
label1:
LOOP
FETCH cursor_Tables into tbName;
IF (SQLSTATE ='02000') THEN
LEAVE label1;
END IF;
CASE WHEN (
SELECT COUNT(*)
FROM prd3_db_tmd.K_PTY_NK01
WHERE id = 0 ) > 0
THEN tbName
END
END LOOP label1;
CLOSE cursor_Tables;
END;</pre>
<p>How should I solve this problem? Do I need to use additional stored procedures? The DBMS is Teradata. </p>
If this is SQL Server you can look at the following SQL Cursors, I edited the cursor declaration and the code in it Although they may be different from your requirements, I think you can modify them easily
declare @sql nvarchar(max) declare @tablename nvarchar(100) DECLARE cursor_Tables CURSOR FOR SELECT s.name + '.' + o.name --s.name [schema], o.name [table] FROM sys.Columns c inner join sys.objects o on c.object_id = o.object_id inner join sys.schemas s on s.schema_id = o.schema_id WHERE c.Name ='id' and o.type = 'U' /* SELECT TableName, DatabaseName +'.'+ TableName, ColumnName FROM DBC.Columns WHERE ColumnName = 'id' */ OPEN cursor_Tables; FETCH NEXT FROM cursor_Tables INTO @tablename WHILE @@FETCH_STATUS = 0 BEGIN -- print @tablename set @sql = 'select case when count(*) > 0 then ''' + @tablename + ''' else '''' end from ' + @tablename exec sp_executesql @sql FETCH NEXT FROM cursor_Tables INTO @tablename END CLOSE cursor_Tables; DEALLOCATE cursor_Tables;You need a stored procedure because this is the only place where cursors can be used in Teradata.
REPLACE PROCEDURE testproc() DYNAMIC RESULT SETS 1 BEGIN DECLARE tbName VARCHAR(257); DECLARE SqlStr VARCHAR(500); -- 临时表来存储结果集 CREATE VOLATILE TABLE _vt_(tbName VARCHAR(257)) ON COMMIT PRESERVE ROWS; -- 您现有的查询来返回表名 -- 最好使用ColumnsV而不是Columns FOR cursor_Tables AS SELECT DatabaseName || '.' || TABLENAME AS tbName FROM DBC.ColumnsV WHERE ColumnName ='id' DO -- 准备动态SQL ... SET SqlStr = 'insert into _vt_ select ''' || cursor_tables.tbName || ''' from ' || cursor_tables.tbName || ' where id = 0 having count(*) > 0; '; -- ... 并执行它 EXECUTE IMMEDIATE SqlStr; END FOR; BEGIN -- 返回结果集 DECLARE resultset CURSOR WITH RETURN ONLY FOR S1; SET SqlStr = 'SELECT * FROM _vt_;'; PREPARE S1 FROM SqlStr; OPEN resultset; END; DROP TABLE vt; END;