Last active
July 16, 2023 13:14
-
-
Save exemplum100/d2776e5931466c4c3119d6c8f430a682 to your computer and use it in GitHub Desktop.
Cursor Sample, declare for tables list. Result select values from list of tables, with equal(!) column names
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--Cursor Sample, declare for tables list-- | |
--Result select val from list of tables, with equal column names-- | |
IF OBJECT_ID('tempdb..#connector1') IS NOT NULL DROP TABLE #connector1 | |
IF OBJECT_ID('tempdb..#resulttable') IS NOT NULL DROP TABLE #resulttable | |
CREATE TABLE #connector1 (val int) | |
CREATE TABLE #resulttable (id int, val int) | |
DECLARE | |
@tablename VARCHAR(100), | |
@id int, | |
@query VARCHAR(100), | |
@maxval | |
DECLARE cname CURSOR LOCAL FOR | |
SELECT id, table_name FROM tables --select unique id with tablename from table list | |
OPEN cname | |
FETCH NEXT FROM cname | |
INTO @id, @tablename --@id for #resulttable, @tablename for #connector | |
WHILE @@FETCH_STATUS=0 | |
BEGIN | |
SET @query ='SELECT max(val) from ' +@tablename --select each needed val from each table | |
INSERT INTO #connector1 --example to take vaL into vaR, cos 'exec' has some restricts | |
EXEC(@query) -- ....and insert one val from EXEC-query into 'dynamic-one-val-table' :) | |
SELECT top(1) @maxval = val from #connector1 --select val into @var from dynamic table for #resulttable | |
TRUNCATE TABLE #connector1 --clear 'dynamic' table | |
INSERT INTO #resulttable | |
SELECT @id, @maxval --insert into result table two values, @id from tablenames, @maxval for this table | |
FETCH NEXT FROM cname | |
INTO @id,@tablename | |
END | |
CLOSE cname | |
DEALLOCATE cname | |
/************************* | |
Needed val with expand info: | |
SELECT r.val as values, t.table_name FROM tables as t | |
JOIN #resulttable as r on t.id=r.id | |
*************************/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment