Skip to content

Instantly share code, notes, and snippets.

@exemplum100
Last active December 19, 2024 05:44
Show Gist options
  • Save exemplum100/2f5dd7c7469dca4a059a7ae395e157c9 to your computer and use it in GitHub Desktop.
Save exemplum100/2f5dd7c7469dca4a059a7ae395e157c9 to your computer and use it in GitHub Desktop.
Пример запроса sql для сверки значений из списка таблиц
--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) -- insert one val from EXEC-query into 'dynamic-one-val-table'
SELECT top(1) @maxval = val from #connector1 --...and 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
/*************************
Finaly, 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