如何在子句中的存储过程中使用参数

时间:2018-05-04 10:53:32

标签: sql-server visual-studio

我需要使用存储过程更新表。

在该存储过程中,我使用IN子句来表示某些特定的行,这里我使用的字符串具有类似于这样的值='AC101','AC102','AC103'

例如:

string Recipt = "'AC101','AC102','AC103'";

此外,我存储的程序查询是

@PaymentDate nvarchar(MAX),
@ReciptNo nvarchar(50)

AS
BEGIN

    SET NOCOUNT ON;
update Monthly_Payment set Payment_Date = @PaymentDate where Recipt_No in (@ReciptNo );

END

它正在执行查询但不更新字符串

中提到的记录

注意:

如果我使用普通查询,则会成功更新。

例如:

update Monthly_Payment set Payment_Date = @PaymentDate where Recipt_No in (@ReciptNo );

请更新。

2 个答案:

答案 0 :(得分:1)

DECLARE @MonthlyPayment TABLE
(
  PaymentDate NVARCHAR(10) ,
  ReceiptNo NVARCHAR(50)
);

INSERT  INTO @MonthlyPayment
    ( PaymentDate, ReceiptNo )
VALUES  ( '2018-01-13', 'AC102' ),
    ( '2018-01-11', 'AC101' ),
    ( '2018-02-10', 'AC103' );

DECLARE @PaymentDate NVARCHAR(MAX)= '2018-05-04' ,
@ReceiptNo NVARCHAR(50)= N'AC101,AC102,AC103';


UPDATE  @MonthlyPayment
SET     PaymentDate = @PaymentDate
WHERE   ReceiptNo IN ( SELECT   value
                   FROM     STRING_SPLIT(@ReceiptNo, ',') ); 
/*The STRING_SPLIT function is available only under compatibility level   130. If your database compatibility level is lower than 130, SQL Server will    not be able to find and execute */
SELECT  PaymentDate ,
    ReceiptNo
FROM    @MonthlyPayment;

答案 1 :(得分:0)

尝试这个答案肯定会对你有用

第1步:首先创建此功能。只需运行以下代码

CREATE FUNCTION [dbo].[StringSplitToTable]  
    (  
      @Input NVARCHAR(MAX) ,  
      @Character CHAR(1)  
    )  
RETURNS @Output TABLE ( Item VARCHAR(500) )  
AS   
    BEGIN  
        DECLARE @StartIndex INT ,  
            @EndIndex INT  
        SET @StartIndex = 1  
        IF SUBSTRING(@Input, LEN(@Input) - 1, LEN(@Input)) <> @Character   
            BEGIN  
                SET @Input = @Input + @Character  
            END  
        WHILE CHARINDEX(@Character, @Input) > 0   
            BEGIN  
                SET @EndIndex = CHARINDEX(@Character, @Input)  
                INSERT  INTO @Output  
                        ( Item  
                        )  
                        SELECT  SUBSTRING(@Input, @StartIndex, @EndIndex - 1)  
                SET @Input = SUBSTRING(@Input, @EndIndex + 1, LEN(@Input))  
            END  
        RETURN  
    END 

第2步:

此更新查询将类似于以下

注意:确保数据格式为@ ReciptNo ='AC101,AC102,AC103'

update Monthly_Payment set Payment_Date = @PaymentDate where Recipt_No in (select item from StringSplitToTable(@ReciptNo,',') );