查询从TVP添加多个名称

时间:2013-08-12 17:09:45

标签: sql-server

我有一个像这样的名称值对的表

属性 - EmployeeId

我的员工表格如下: -

EmployeeId  FirstName Middle LastName

1           John             Smith

2           Rick      Steve  James

3           Maddy     Y      Angela

现在我的TVP可以包含多个或单个EmployeeId

我想在一个参数中添加TVP中所有人的全名。

例如。如果我在TVP中收到1和3

我的输出应该是John Smith,Maddy Y Angela。

我是否需要使用游标?

实现这一目标的最佳方法是什么?

修改

TVP的Scipt如下: -

CREATE TYPE [dbo].[Employee] AS TABLE(    [EmployeeId] [uniqueidentifier] NULL)GO

所需的输出是TVP逗号中的员工全名。

2 个答案:

答案 0 :(得分:1)

假设你有一个类似的表类型:

CREATE TYPE dbo.TVPTypeName AS TABLE(EmployeeId INT PRIMARY KEY);

然后你可以只进行一次加入:

CREATE PROCEDURE dbo.foo
  @bar dbo.TVPTypeName READONLY
AS
BEGIN
  SET NOCOUNT ON;

  SELECT STUFF((SELECT ',' 
    + e.FirstName 
    + COALESCE(' ' + NULLIF(RTRIM(e.Middle),''), ' ') 
    + e.LastName 
  FROM dbo.Employees AS e
  INNER JOIN @bar AS b
  ON e.EmployeeId = b.EmployeeId
  FOR XML PATH(''),TYPE).value('.[1]','nvarchar(max)'),1,1,'');
END
GO

答案 1 :(得分:0)

CREATE TYPE dbo.IntArray AS TABLE(IntValue INT PRIMARY KEY);
GO
CREATE TABLE dbo.Employee(
    EmployeeID INT IDENTITY(1,1) PRIMARY KEY,
    FirstName NVARCHAR(50) NOT NULL,
    MiddleName NVARCHAR(50) NULL,
    LastName NVARCHAR(50) NOT NULL
);
GO
INSERT INTO dbo.Employee VALUES ('John',NULL,'Smith');
INSERT INTO dbo.Employee VALUES ('Rick','Steve','James');
INSERT INTO dbo.Employee VALUES ('Maddy','Y','Angela');
GO
CREATE PROCEDURE dbo.CocoJambo(@pEmployee dbo.IntArray READONLY)
AS
BEGIN
    DECLARE @Result NVARCHAR(MAX);
    SELECT @Result=ISNULL(@Result,'')+','+FirstName+ISNULL(' '+MiddleName,'')+' '+LastName
    FROM dbo.Employee e INNER JOIN @pEmployee p ON e.EmployeeID=p.IntValue;
    SELECT STUFF(@Result,1,1,'') AS [Result];
END;
GO
-- Test
DECLARE @p dbo.IntArray;
INSERT INTO @p VALUES (1);
INSERT INTO @p VALUES (3);
EXEC dbo.CocoJambo @pEmployee=@p;
/*
Result
-------------------------
John Smith,Maddy Y Angela
*/