SELECT rows that have specified values in one of the columns

≯℡__Kan透↙ 提交于 2019-12-08 08:17:45

问题


I have the following table on my SQL Server 2012:

ID Name Status Address Phone
1  Tom    I       U      D
2  Joe    D       U      D
3  Pam    D       I      U
4  Ken    U       U      U

How do I select the rows with 'I' in one of the columns? for example, I expect the query to return 1st and 3rd row from the table.

I know the query below works however I need a query that does not specify the column names as I need to deal with a table with more than 20 columns.

SELECT * FROM table WHERE (Status = 'I' or Address = 'I' or Phone = 'I')

回答1:


One way is to use XML:

SELECT t.*
FROM tab t
CROSS APPLY (SELECT * FROM tab t2 WHERE t.id = t2.id FOR XML RAW('a')) sub(c)
WHERE sub.c LIKE '%"I"%';

Output:

┌────┬──────┬────────┬─────────┬───────┐
│ ID │ Name │ Status │ Address │ Phone │
├────┼──────┼────────┼─────────┼───────┤
│  1 │ Tom  │ I      │ U       │ D     │
│  3 │ Pam  │ D      │ I       │ U     │
└────┴──────┴────────┴─────────┴───────┘

DBFiddle Demo


EDIT:

A bit more advanced option that excludes some columns. Basically simulating SELECT * EXCEPT id, name:

SELECT DISTINCT t.*
FROM tab t
CROSS APPLY (VALUES(CAST((SELECT t.* for XML RAW) AS xml))) B(XMLData)
CROSS APPLY (SELECT 1 c
             FROM B.XMLData.nodes('/row')  AS C1(n)
             CROSS APPLY C1.n.nodes('./@*') AS C2(a)
             WHERE a.value('local-name(.)','varchar(100)') NOT IN ('id','name')
               AND a.value('.','varchar(max)')  = 'I') C;

DBFiddle Demo2




回答2:


I don't know a way of doing your query without making any mention of column names. Here is one method which uses a string concatenation trick:

SELECT *
FROM yourTable
WHERE CONCAT(Status, Address, Phone) LIKE '%I%';

Demo

I don't think it is too difficult to list out 20 column names, once, in a query. If you need a way to get all columns from a table in SQL Server, then see here.



来源:https://stackoverflow.com/questions/50850561/select-rows-that-have-specified-values-in-one-of-the-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!