SQL:select 中的简单自定义列不起作用?

SQL: simple custom column in select doesn't work?

如果我在 select 中添加自定义列,我会收到此错误:

20018 Invalid column name '2'.

这是查询示例

SELECT
    [msg].[MessageTo],
    [msg].[MessageFrom],
    [msg].[SendTime],
    [msg].[ReceiveTime],
    [msg].[id],
    '2' AS source,
    [kat].[id] AS [CategoriId],
    [kat].[naziv] AS [CategoriName]
FROM
    [SMSServer_1].[dbo].[MessageIn] AS [msg]
LEFT JOIN [Tekijanka].[dbo].[crm_poruka] AS [por] ON [por].[fk_poruka] = [msg].[id]
AND [por].[fk_source] = [2]
LEFT JOIN [Tekijanka].[dbo].[crm_kategorije_poruka] AS [kat] ON [kat].[id] = [por].[fk_kategorija]
WHERE
    msg.id NOT IN (
        SELECT
            fk_poruka
        FROM
            Tekijanka.dbo.crm_poruka
        WHERE
            fk_status <> 1
    )
ORDER BY
    [SendTime] DESC

有什么办法可以解决吗?

问题出在 LEFT JOIN,而不是 SELECT 部分:

AND [por].[fk_source] = [2]

此条件尝试连接 fk_source 和列 named [2]。当然,表 MessageIncrm_poruka 中没有这样的列。您必须更改这部分代码(删除条件或将其更改为AND [por].[fk_source] = 2)。