SQL Server SQL IN Operator for Concatenated values

tvokkenx  于 2023-06-04  发布在  其他
关注(0)|答案(2)|浏览(123)
IDNews_CodeNews_Digits
1GBX400
2NXC670
3LBO880

I have several codes, what I need to check that code are in News_Code & news_Digit section. My code is like this:

'LBX 345','NXC 670'

What I have tried:

SELECT * 
FROM tblNews 
WHERE News_Code IN ('LBX 345', 'NXC 670')` // But here is the problem is not only the news_code we need to consider the News_Digit as well.
iezvtpos

iezvtpos1#

You can concatenate the two columns and then compare:

SELECT * 
FROM tblNews 
WHERE News_Code + ' ' + News_Digits IN ('LBX 345', 'NXC 670')

If News_Digits is not a string data type, you can change that by casting it:

SELECT * 
FROM tblNews 
WHERE News_Code + ' ' + CAST(News_Digits AS VARCHAR(3)) IN ('LBX 345', 'NXC 670')
gcxthw6b

gcxthw6b2#

You can join a VALUES virtual table (or use a real table variable, Table Valued Parameter or temp table)

SELECT n.*
FROM tblNews n
JOIN (VALUES
  ('LBX', 345),
  ('NXC', 670)
) v(News_Code, News_Digits)
  ON v.News_Code = n.News_Code
 AND v.News_Digits = n.News_Digits;

相关问题