我正在写这个表函数
CREATE FUNCTION udf_RealEstateAgentSales
(@FirstName NVARCHAR, @SecondName NVARCHAR, @LastName NVARCHAR)
RETURNS @salesAmoutAndAgent TABLE (FirstName NVARCHAR(25),
SecondName NVARCHAR(25),
LastName NVARCHAR(25),
sales INT)
AS
BEGIN
DECLARE @sales INT;
SET @sales = COUNT(*);
INSERT @salesAmoutAndAgent
SELECT @FirstName, @SecondName, @LastName, @sales
FROM Purchases AS P
INNER JOIN Employees AS E ON P.DealMadeByEmployeeID = E.EmployeeID
WHERE
@FirstName = FirstName
AND @SecondName = SecondName
AND @LastName = LastName
RETURN
END
我希望它根据他的名字,姓名和姓氏返回firstName,secondName,lastName和sales ...
但是当我称之为
SELECT *
FROM dbo.RealEstatudf_eAgentSales('somename', 'somename', 'somename');
它返回一个空表......我的错误是什么?
答案 0 :(得分:3)
首先:Bad habits to kick : declaring VARCHAR without (length) - 您应始终为您使用的任何(n)varchar
变量和参数提供长度。如果您使用NVARCHAR
- 那么您会得到完全 1个字符长度的字符串通常而不是您想要的.....为...提供合理的长度你的参数!否则,您在调用中传递的值somename
将被截断为s
.....
下一步:您正在选择,但是您正在使用参数名称(带有前导@
) - 而不是列名称 - 赢得了工作
第三:你的WHERE
条款都错了 - 你需要写它
WHERE (column name) = @(parameter name)
试试这段代码:
CREATE FUNCTION udf_RealEstateAgentSales
(@FirstName NVARCHAR(25),
@SecondName NVARCHAR(25),
@LastName NVARCHAR(25) )
RETURNS @salesAmoutAndAgent TABLE (FirstName NVARCHAR(25),
SecondName NVARCHAR(25),
LastName NVARCHAR(25),
sales INT)
AS
BEGIN
DECLARE @sales INT;
SET @sales = COUNT(*);
INSERT @salesAmoutAndAgent
SELECT
FirstName, SecondName, LastName, sales
FROM
Purchases AS P
INNER JOIN
Employees AS E ON P.DealMadeByEmployeeID = E.EmployeeID
WHERE
FirstName = @FirstName
AND SecondName = @SecondName
AND LastName = @LastName
RETURN
END
另外:那行
SET @sales = COUNT(*);
根本没有任何意义 - 你需要重新思考(并重新编码)这个更有意义的东西......你从