Rumah > Soal Jawab > teks badan
P粉2210464252023-08-17 11:13:22
Jika ini SQL Server, anda boleh melihat yang berikut SQL Cursor, saya telah mengedit pengisytiharan kursor dan kod di dalamnya Walaupun ia mungkin berbeza daripada keperluan anda, saya rasa anda boleh mengubah suainya dengan mudah
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;
P粉7524794672023-08-17 09:39:26
Anda memerlukan prosedur tersimpan kerana ini adalah satu-satunya tempat di mana kursor boleh digunakan dalam 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;