我是SQL查询的新手,在这里我试图从dbo.Customer_List表中获取完整的名称,并编写了这段代码。但是,当尝试运行时,我收到以下错误。我不知道自己做错了什么。
错误信息是:
Msg 1087, Level 16, State 1, Procedure getFullName, Line 11
Must declare the table variable "@tblName".
Msg 1087, Level 16, State 1, Procedure getFullName, Line 14
Must declare the table variable "@tblName".
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'Last_Name'.
代码是:
IF OBJECT_ID (N'dbo.getFullName', N'FN') IS NOT NULL
DROP FUNCTION getFullName
GO
Create function dbo.getFullName(@tblName varchar(30),@fstName varchar(50), @lstName varchar(50) ) returns varchar(101)
As
Begin
Declare @rowCount int
Declare @rowIteration int
Declare @temp varchar(101)
Select @rowCount = count(*) from @tblName
Set @rowIteration = 1
While ( @rowIteration <= @rowCount)
Select @temp = @fstName+' '+@lstName from @tblName where @tblName.Customer_Id = @rowIteration
Begin
Set @rowIteration = @rowIteration + 1
End
return @temp
End
Go
Declare @tblName varchar(30),@fstName varchar(50), @lstName varchar(50)
set @tblName = convert(varchar(30),'dbo.Customer_List')
set @fstName = convert(varchar(50),'dbo.Customer_List.First_Name')
set @lstName = convert(varchar(50),'dbo.Customer_List.Last_Name')
Execute ('select dbo.getFullName('+ @tblName+','+ @fstName+','+ @lstName )
答案 0 :(得分:0)
您实际上是在尝试执行动态SQL而不正确执行它。您不能仅将变量作为表名传入,这就是您收到错误的原因。
您需要将其重新创建为存储过程(或者至少您将在sql-server中,它不喜欢函数中的DML事务)并使用以下动态sql:
Declare @sql nvarchar(100)
Set @sql = 'Set @int = (Select count(*) from ' + @tblName + ')'
execute sp_executesql @sql, N'@int int output', @int = @rowCount output