Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

sql server - Query to search in all columns in table with joining

I am searching in all column data in the selected SQL table, and I have a join with another table, but my issue that the 2nd table has the same column name with tableA, how can I specify each column with its table. So I declare the string to find and the table, if I remove the join it will work, but my issue only with joining

DECLARE @stringToFind varchar(max) ='%TELECOM%'
DECLARE @table varchar(max) ='tableA'
DECLARE @sqlCommand varchar(max) = 'SELECT * FROM [' + @table + '] 
Left join    Table2 on
               Table2.Id= tableA.IdCategory  
WHERE ' 
SELECT @sqlCommand = @sqlCommand + '[' + COLUMN_NAME + '] LIKE ''' + @stringToFind + ''' OR '
FROM INFORMATION_SCHEMA.COLUMNS 

WHERE TABLE_NAME = @table 
AND DATA_TYPE IN ('char','nchar','ntext','nvarchar','text','varchar')

SET @sqlCommand = left(@sqlCommand,len(@sqlCommand)-3)
EXEC (@sqlCommand)
PRINT @sqlCommand

Ambiguous column name 'Type'.

question from:https://stackoverflow.com/questions/65952657/query-to-search-in-all-columns-in-table-with-joining

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

"Select *" will return all columns from both joined tables. If both tables have a column with the same name it will be ambiguous.

Table qualifiers may help. Explicitly select the columns you want.

select T1.type atype,T2.type another_type, T1.*,T2.* from Table1 as T1 left join Table2 as T2 on T1.columnName= T2.columnName

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...