条件与 IN() 语句不匹配的空白结果

Blank result for criteria not matching IN() statement

我有一个很大的 ID 列表,我需要从数据库中填充一些信息。我希望我的查询结果显示数据中的差距。这很难描述,但鉴于此数据:

这个查询:

SELECT ID, Name, Color FROM myTable
WHERE ID IN ('1','2','3','4','5','6','7')

我想要这些结果:

这可能吗?

您可以使用递归 CTE 创建 table 个值,然后加入该 table 以查找缺失值。

;with CTE AS (
SELECT 1 AS col_

UNION ALL 

SELECT 1 + col_
FROM cte

WHERE col_ <100
)

SELECT col_, mt.*
FROM cte

LEFT JOIN myTable mt
ON mt.id = col_

正在使用函数....

CREATE FUNCTION dbo.BreakStringIntoRows (@CommadelimitedString   varchar(1000))
RETURNS   @Result TABLE (Ret VARCHAR(100))
AS
BEGIN
        DECLARE @IntLocation INT
        WHILE (CHARINDEX(',',    @CommadelimitedString, 0) > 0)
        BEGIN
              SET @IntLocation =   CHARINDEX(',',    @CommadelimitedString, 0)      
              INSERT INTO   @Result (Ret)
              --LTRIM and RTRIM to ensure blank spaces are   removed
              SELECT RTRIM(LTRIM(SUBSTRING(@CommadelimitedString,   0, @IntLocation)))   
              SET @CommadelimitedString = STUFF(@CommadelimitedString,   1, @IntLocation,   '') 
        END
        INSERT INTO   @Result (Ret)
        SELECT RTRIM(LTRIM(@CommadelimitedString))--LTRIM and RTRIM to ensure blank spaces are removed
        RETURN 
END

Select 声明

SELECT 
    Id = B.Ret, 
    Name = ISNULL(T.Name, ''), 
    Color = ISNULL(T.Color, '') 
FROM dbo.BreakStringIntoRows('1,2,3,4,5,6,7') AS B
LEFT JOIN myTable T ON B.Ret = T.Id

结果

希望对您有所帮助。