P
P
pulsework2021-12-06 13:52:31
SQL Server
pulsework, 2021-12-06 13:52:31

Is it possible to access a table in a nested select in where without knowing its name?

select some_column_name
from some_table
where some_column_name < (select max(some_column_name) from some_table)
--  как в этом месте узнать и/или указать имя или ссылку или какой-то алиас для some_table

In the program for the end user, only where is available for modification, and the name of the source table is unknown and is generally dynamically formed according to a rule inaccessible to the limited end user. The column names are known.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Konstantin Tsvetkov, 2021-12-06
@pulsework

Start with:

SELECT sys.tables.[name] AS 'TableName',
       sys.columns.[name] AS 'ColumnName'
FROM sys.columns 
  INNER JOIN sys.tables ON sys.columns.object_id = sys.tables.object_id
WHERE sys.columns.[name] LIKE '%ID%'
ORDER BY 1, 2

And if you just need to display all values ​​except the maximum, then:
WHERE 1=1 ORDER BY some_column_name DESC OFFSET 1 ROWS

How to address select with a table object

DECLARE @SQL VARCHAR(MAX) = 'SELECT * FROM '
SELECT @SQL = @SQL + sys.tables.[name] FROM sys.columns 
  INNER JOIN sys.tables ON sys.columns.object_id = sys.tables.object_id
WHERE sys.columns.[name] = 'some_column_name'
EXECUTE( @SQL )

The Curse and Blessings of Dynamic SQL .

P
pulsework, 2021-12-07
@pulsework

thanks, but it didn’t fit, from the catch of the question, only the where field is available for modification,
but there are no solutions, only through exec

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question