1

我想要创建函数,它使用表名作为参数。当我搜索时,我需要使用动态 sql。我尝试这样的代码:

CREATE FUNCTION get_column_id
    (
    @TableName VARCHAR(30),
    @ColumnName VARCHAR(30),
    )
RETURNS int 
AS
BEGIN
IF EXISTS 
    (
    DECLARE @SQL VARCHAR(50)
    SET @sql = 'SELECT' + @ColumnName + 'FROM' + @TableName + 'WHERE @ColumnName =    @ColumnNameValue';
    EXEC(@sql)
    )
BEGIN

但是会出错。有什么方法可以进行吗?

我尝试以这种方式使用动态sql

DECLARE @SQL VARCHAR(50)
SET @SQL = 'SELECT' + @ColumnName + 'FROM' + @Table + 'WHERE @ColumnName = @ColumnNameValue'
EXEC(@SQL)
DECLARE @TableName table (Name VARCHAR(30))
INSERT INTO @TableName VALUES (@SQL)
IF EXISTS 
    (SELECT Name FROM @TableName WHERE Name = @ColumnNameValue)

但是得到Invalid use of a side-effecting operator 'EXECUTE STRING' within a function. 有谁知道如何绕过这个约束?

4

2 回答 2

2

错误是字符串之间缺少空格的连接,

SET @sql = 'SELECT ' + @ColumnName + ' FROM ' + @TableName + ' WHERE ' + @ColumnName + ' = ' + @ColumnNameValue;
               -- ^ SPACE HERE        ^    ^                  ^ and here

例如,如果列的数据类型是字符串,则需要用单引号将值括起来,

SET @sql = 'SELECT ' + @ColumnName + ' FROM ' + @TableName + ' WHERE ' + @ColumnName + ' = ''' + @ColumnNameValue + '''';

更新 1

您还需要声明参数@ColumnNameValue,例如

CREATE FUNCTION get_column_id
(
    @TableName VARCHAR(30),
    @ColumnName VARCHAR(30),
    @ColumnNameValue VARCHAR(30)
)
于 2013-03-20T13:30:36.030 回答
1

Sql Server 中的 UDF(用户定义函数)必须是确定性的。除了语法错误之外,您将无法完成任务。

如果您查看 MSDN 上的这篇文章:

http://msdn.microsoft.com/en-us/library/ms178091.aspx

你可以看到下面的引用:

Deterministic functions always return the same result any time they are called 
with a specific set of input values and given the same state of the database.    

Nondeterministic functions may return different results each time they are 
called with a specific set of input values even if the database state that 
they access remains the same.
于 2013-03-20T13:46:55.663 回答