SQL Server:获取其中发现行

时间:2017-06-06 12:00:35

标签: sql sql-server database

我在解决这个问题上遇到了困难。我正在使用Microsoft SQL Server 2014(版本12.0.4100.1)。

我有两张表contactsbusiness。我有一系列联系人用户名。我正在使用WHERE中的子查询从此用户名数组中获取业务列表,如下所示:

SELECT business.id, business.name, business.notes
FROM business
WHERE business.id IN (SELECT contacts.business_id
                      FROM contacts
                      WHERE contacts.username IN ('username1', 'username2', 'username3'))

此查询工作正常,但我无法弄清楚如何选择找到每一行的值;例如:如果我从用户名'username1'的联系人处获取业务,我想获取它并查看结果:

business.id = 1
business.name = 'Business 1'
business.notes = 'Notes from business 1.'
contacts.username = 'username1'

得到这个结果,我可以很容易地看到每个企业的联系方式。

提前谢谢!

编辑:每个企业可能有多个联系人,因此执行INNER JOIN会为每个联系人返回重复的业务结果。我想确切地知道在子查询中选择的那个是什么联系人。

1 个答案:

答案 0 :(得分:3)

我认为您正在寻找DECLARE @SearchStr nvarchar(100) SET @SearchStr = '%test%' DECLARE @Results TABLE( TableName nvarchar(256), ColumnName nvarchar(370), ColumnValue nvarchar(3630)) SET NOCOUNT ON DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110) SET @TableName = '' SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''') WHILE @TableName IS NOT NULL BEGIN SET @ColumnName = '' SET @TableName = ( SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName AND OBJECTPROPERTY( OBJECT_ID( QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) ), 'IsMSShipped' ) = 0 ) WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL) BEGIN SET @ColumnName = ( SELECT MIN(QUOTENAME(COLUMN_NAME)) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2) AND TABLE_NAME = PARSENAME(@TableName, 1) AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar') AND QUOTENAME(COLUMN_NAME) > @ColumnName ) IF @ColumnName IS NOT NULL BEGIN INSERT INTO @Results EXEC ( 'SELECT DISTINCT ''' + @TableName + ''',''' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) FROM ' + @TableName + ' (NOLOCK) ' + ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2 ) END END END SELECT TableName, ColumnName, ColumnValue FROM @Results

join