SQL Server 返回用逗号隔开的字符串

  DECLARE @TempTable TABLE (ID INT IDENTITY(1,1),Name NVARCHAR(100),Lessons NVARCHAR(100))
  INSERT INTO @TempTable ( Name, Lessons )
  SELECT '张三','语文' UNION ALL
  SELECT '李四','数学' UNION ALL
  SELECT '张三','数学' UNION ALL
  SELECT '张三','英语' UNION ALL
  SELECT '李四','语文'
  SELECT * FROM @TempTable

   
  --返回用逗号隔开的字符串

  --定义的变量一定要先初始化赋值,否则查询等于空
  DECLARE @Lessons NVARCHAR(max)=''
  SELECT  @Lessons=@Lessons+ISNULL(A.Lessons,'')+',' from @TempTable  AS A   WHERE Name='张三'
  SELECT @Lessons AS 'Lessons'

 

  

转载于:https://www.cnblogs.com/MoMo1002/p/6856616.html

你可能感兴趣的:(SQL Server 返回用逗号隔开的字符串)