我想要create table,它使用表名作为参数。在我搜索时我需要使用动态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.
有谁知道如何绕过这个约束?
答案 0 :(得分: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)
)
答案 1 :(得分: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.