在SQL Server中的一个参数中传递多个值

时间:2014-12-08 09:45:16

标签: sql sql-server-2005

Create procedure [dbo].[sp_Sample]
    @param1 varchar(100)
as
   DECLARE @Sql VARCHAR(MAX)
   SET @param1 = REPLACE(@param1,',',''',''')
   SET @Sql = 'select * from tblSample where col1 IN (''' + @param1 + ''')'
Go

DECLARE @return_value int

EXEC @return_value = [dbo].[sp_Sample]
     @Escalation = N'SIM4'

SELECT  'Return Value' = @return_value
GO

执行此程序时,不显示任何内容

建议我,如果有什么不对

由于

2 个答案:

答案 0 :(得分:0)

您没有执行动态查询,请尝试以下操作:

CREATE PROCEDURE [dbo].[sp_Sample] @param1 VARCHAR(100)
AS
    DECLARE @Sql NVARCHAR(MAX)

    SET @param1 = Replace(@param1, ',', ''',''')
    SET @Sql = 'select * from tblSample where col1 IN ('''
               + @param1 + ''')'
    --PRINT @Sql 
    exec sp_executesql @Sql
GO 

Exec sp_Sample '1001'
GO

注意:PRINT语句将打印查询字符串,取消注释并检查您的查询。

答案 1 :(得分:0)

有许多事情需要在这里更新:

CREATE PROCEDURE [dbo].[sp_Sample] 
@param1 nvarchar(100),-- change 1 as you have added N for  @Escalation
@return int OUTPUT -- change 2: define output variable for value the sp will return
AS  

    SET NOCOUNT ON;
    DECLARE @SQLString nvarchar(500);
    DECLARE @ParmDefinition nvarchar(500);

    /* Build the SQL string one time.*/
    SET @SQLString =
         N'SELECT @return_valueOUT = Id from tblSample where col1 
         IN (''' + @param1 + ''')' ;

    SET @ParmDefinition = N'@return_valueOUT int OUTPUT';

    -- dynamically execute the query
    EXECUTE sp_executesql @SQLString, @ParmDefinition,
            @return_valueOUT=@return OUTPUT;

RETURN
GO

-- Declare the variable to receive the output value of the procedure.
DECLARE @return_value int;
-- Execute the procedure specifying a input parameter
-- and saving the output value in the variable @return_value
EXECUTE [dbo].[sp_Sample] N'Test', @return = @return_value OUTPUT;
-- Display the value returned by the procedure.
-- as @return_value is an int cast it to varchar
Select 'Return Value = '  + convert(varchar(10),@return_value); 
GO

DEMO