在Sql Server 2005中创建UDF时出错

时间:2011-03-07 07:20:04

标签: sql-server-2005

有谁知道这个代码块有什么问题。

CREATE FUNCTION [dbo].[udfGetPoint]
(
    @UserID INT,
    @SqlCountry VARCHAR(1000)
)
RETURNS INT
AS
BEGIN
    DECLARE @Points INT
    SET @Points = 1
    DECLARE @RecordCount sysname
    IF @SqlCountry <> ''
    BEGIN
        EXEC sp_executesql
        N'SELECT @DynamicCount = COUNT(UserID) FROM Country WHERE UserID = '+@UserID+' AND LCValues IN (' + @SqlCountry + ')'
        ,N'@DynamicCount sysname OUTPUT'
        ,@RecordCount OUTPUT
        IF @RecordCount > 0
            SET @Points = @Points + 1
    END

    RETURN @Points
END

如果我执行此操作,我会收到以下错误:

Msg 102, Level 15, State 1, Procedure udfGetPoint, Line 15
Incorrect syntax near '+'.

1 个答案:

答案 0 :(得分:0)

您无法在存储过程的参数设置中进行连接。

DECLARE @sql varchar(2000)

SET @SQL = 'SELECT @DynamicCount = COUNT(UserID) FROM Country WHERE UserID = '+@UserID+' AND LCValues IN (' + @SqlCountry + ')'

EXEC sp_executesql
        @SQL
        ,N'@DynamicCount sysname OUTPUT'
        ,@RecordCount OUTPUT