如何从SQL Server中的单个参数中获取多个值

时间:2017-07-31 04:14:15

标签: c# sql-server stored-procedures parameters

请帮助我解决以下问题。

我想从单个参数中获取多个值到SQL Server中的过程,我学习SQL和C#。

这是我的代码:

ALTER PROCEDURE AProc_Getback 
    (@fcode VARCHAR(10))
AS
BEGIN
    UPDATE t_PALM_PersonnelFileMst 
    SET fdflag = 0, frdate = null, fddate = null,
        fdtype = null, fdreason = null
    WHERE fcode IN ('@fcode')

    DELETE FROM t_pald_dimissiontrm 
    WHERE fcode IN ('@fcode')
END

Exec AProc_Getback '512888,512889'

非常感谢

3 个答案:

答案 0 :(得分:3)

Use Table-Valued Parameters

CREATE TYPE FCodes AS TABLE ( 
    Code VARCHAR(32) -- Use type of "fcode" column
);

存储过程

ALTER PROCEDURE AProc_Getback 
(
    @fcode FCodes
)
AS
BEGIN
    UPDATE t_PALM_PersonnelFileMst SET
        fdflag = 0,
        frdate = null,
        fddate = null,
        fdtype = null, 
        fdreason = null
    WHERE fcode IN (SELECT Code FROM @fcode)

    DELETE FROM t_pald_dimissiontrm 
    WHERE fcode IN (SELECT Code FROM @fcode)
END

执行

DECLARE @Codes AS FCodes
INSERT INTO @Codes VALUES ('123'), ('456'), ('789')

EXEC AProc_Getback @Codes

从C#中,您可以创建SqlDbType.Structure类型的参数,并将DataTable作为值,并将其传递给存储过程

var codesParameter = new SqlParameter
{
    ParameterName = "@fcodes",
    SqlDbType = SqlDbType.Structure,
    TypeName = "dbo.FCodes", // Important! - name of type in database
    Value = dataTableOfCodes // Should contain column with name "Code"
};

using (var connection = new SqlConnection(connectionString)) 
using (var command = connection.CreateCommand()) 
{
    command.CommandText = "dbo.AProc_Getback";
    command.CommandType = CommandType.StoredProcedure;
    command.Parameters.Add(codesParameter);

    connection.Open();
    command.ExecuteNonQuery();
}

答案 1 :(得分:0)

首先,您的参数必须能够保存传入数据。目前,它只能接收最多10个字符的数据。请参阅@fcode varchar(10)

如果您没有可用的分割功能,则可以创建一个。或者,您可以使用一些内联代码来实现这一点。例如:

ALTER PROCEDURE AProc_Getback(@Fcode VARCHAR(MAX))
AS
BEGIN

    CREATE TABLE #FCodes (Item  VARCHAR(30));
    DECLARE @Insert VARCHAR(MAX) = 'INSERT INTO #FCodes VALUES ('''+REPLACE(@Fcode,',','''),(''')+''');';
    EXEC (@Insert);   


    UPDATE t_PALM_PersonnelFileMst
    SET
        fdflag = 0,
        frdate = NULL,
        fddate = NULL,
        fdtype = NULL,
        fdreason = NULL
    WHERE fcode IN(SELECT Item FROM #FCodes);


    DELETE FROM t_pald_dimissiontrm
    WHERE fcode IN(SELECT Item FROM #FCodes);
END;

答案 2 :(得分:-1)

I/RECVEIVED: delay 1: Mon Jul 31 06:08:58 GMT+02:00 2017
I/RECVEIVED: delay 2: 1501474138319

然后

  Alter PROCEDURE AProc_Getback ( @fcode varchar(Max)

    ) AS

    Begin update t_PALM_PersonnelFileMst set fdflag = 0,frdate = null,fddate = null,fdtype = null, fdreason = null where fcode in (select Item
from dbo.SplitString(@fcode, ',')) 
    delete from t_pald_dimissiontrm where fcode in (select Item
from dbo.SplitString(@fcode, ',')) end