我需要创建SQL函数以获取传递Id和表名称时的名称

时间:2017-03-23 12:30:25

标签: sql-server-2008

ALTER FUNCTION [dbo].[getName](@Id int,@Table_Name sysname,@col_name nvarchar(30),@col_condition)
RETURNS nvarchar(400)
AS
BEGIN
    DECLARE @r nvarchar(250)
    DECLARE @DynamicSQL nvarchar(4000)
    SET @DynamicSQL = N'SELECT '+@sl_col+' FROM ' + @Table_Name +' WHERE     @col_condition='+ @id
    EXECUTE sp_executesql @DynamicSQL
   set @r=EXECUTE sp_executesql @DynamicSQL
    RETURN @r
END

考试:

SELECT Emp_Name FROM Emp WHERE emp_id=1

1 个答案:

答案 0 :(得分:0)

ALTER FUNCTION [dbo].[getName]
(@id int,@Table_Name sysname,@col_name nvarchar(30),@col_condition) 

RETURNS nvarchar(400) 

AS BEGIN 

DELCARE @r varchar(50)
DECLARE @DynamicSQL nvarchar(4000) 

SET @DynamicSQL = 'SELECT @r = ' + @col_name + ' FROM ' + @Table_Name + ' WHERE ' + @col_condition + ' = ' + @id

EXECUTE (@DynamicSQL)

RETURN @r 

END