如何使用列作为tsql字符串中的输入

时间:2015-03-21 16:26:30

标签: sql sql-server tsql

这是来自my previous post的后续问题。我的问题是,如果我想使用@NameSELECT更改为特定列,我如何将它们连接到SQL字符串?

示例如下:Name表中的Customer列如下所示:

| Name              |          
+-------------------+
| Ben and Jerry.exe |       
| 123od.exe         |             
| m2m.dll           |              
| lyy.exe           |

T-SQL代码:

DECLARE @NameTable = SELECT Name from Customer
DECLARE @Name nvarchar(MAX)  =  = '''' + REPLACE(@NameTable, ',', ''',''') + ''''
DECLARE @sql nvarchar(MAX)= 'SELECT OrderName,
   customer.version,
   count(DISTINCT company.CID) as Counts
FROM [CompanyData] company
  INNER JOIN [vendor] mav on company.CID = mav.CID
  LEFT OUTER JOIN [Customer] customer on company.VendorId = customer.VendorId AND company.DId = customer.DId
WHERE OrderName in' + @Name+ '
  GROUP BY  
         customer.version, OrderName'

EXEC sp_executesql @sql

2 个答案:

答案 0 :(得分:0)

您无法选择DECLARE @NameTable = SELECT Name from Customer等记录 从另一个表中,您可以为它创建一个临时表。

像:

create table #tmpName(Name varchar(max))

insert into #tmpName(Name) SELECT Name from Customer

你的答案:

create table #tmpName(Name varchar(max))

    insert into #tmpName(Name) SELECT Name from Customer

DECLARE @sql nvarchar(MAX)= 'SELECT OrderName,
   customer.version,
   count(DISTINCT company.CID) as Counts
FROM [CompanyData] company
  INNER JOIN [vendor] mav on company.CID = mav.CID
  LEFT OUTER JOIN [Customer] customer on company.VendorId = customer.VendorId AND company.DId = customer.DId
WHERE OrderName in (' +(select Name from #tmpName)+ ') 
  GROUP BY  
         customer.version, OrderName'

EXEC sp_executesql @sql

drop table #tmpName

答案 1 :(得分:0)

要连接列中的所有值,我认为你需要做这样的事情。

DECLARE @name NVARCHAR(MAX)
SET @name = ''

SELECT @name = 
    COALESCE (CASE WHEN @name = ''
                   THEN Name
                   ELSE @name + ',' + Name
    END,'')
FROM 
    Table

这将为您提供列中的所有字符串作为CSV。

如果Table是动态名称,则可以在查询中使用动态SQL。

很抱歉,如果此代码有错误或错误,我没有数据库服务器可以试用。

希望这有帮助