子查询有问题

时间:2014-08-09 17:59:00

标签: sql sql-server subquery

我正在尝试使用创建一个使用子查询的SQL查询,但我不完全确定问题是什么。最终,我希望它返回一个以逗号分隔的字符串的列。获取逗号分隔字符串的SELECT语句可以自行运行,但是当我尝试在另一个SELECT语句中使用它时,它会给我一个错误。这是子查询:

DECLARE @listStr VARCHAR(MAX)
SELECT @listStr = COALESCE(@listStr+',' ,'') + CAST(UpgradeID as varchar(20))
FROM [Table1]
SELECT @listStr

当我在另一个select语句中使用它时,我收到此错误:

Msg 156, Level 15, State 1, Line 10
Incorrect syntax near the keyword 'DECLARE'.
Msg 102, Level 15, State 1, Line 15
Incorrect syntax near ')'.

这是给我这个问题的整个查询:

USE [DB1]

SELECT [UID]
      ,[PID]
      ,[UserName]
      ,(

        DECLARE @listStr VARCHAR(MAX)
        SELECT @listStr = COALESCE(@listStr+',' ,'') + CAST(UID as varchar(20))
        FROM [Table1]
        SELECT @listStr

      ) as result
  FROM [Table1]

2 个答案:

答案 0 :(得分:1)

试试这个

DECLARE @listStr VARCHAR(MAX)

SELECT @listStr = COALESCE(@listStr+',' ,'') + CAST(UpgradeID as varchar(20))
FROM [Table1]

USE [DB1]

SELECT
      [UID]
      ,[PID]
      ,[UserName]
      ,@listStr as result
FROM [Table1]

答案 1 :(得分:0)

您无法在子查询中声明变量,但您可以调用它。 另外,我不明白为什么你在子查询中调用变量两次。

无论如何,请尝试以下方法:

USE [DB1]
DECLARE @listStr VARCHAR(MAX)

SELECT [UID]
  ,[PID]
  ,[UserName]
  ,(

    SELECT @listStr = COALESCE(@listStr+',' ,'') + CAST(UID as varchar(20))
    FROM [Table1]

  ) as result
FROM [Table1]