Rumah >pembangunan bahagian belakang >C++ >Bagaimana untuk lulus array ke prosedur yang disimpan SQL Server?
lulus array ke prosedur penyimpanan SQL Server
SQL Server 2016 (atau versi yang lebih tinggi)
string_split ()
<code class="language-sql">CREATE PROCEDURE dbo.DoSomethingWithEmployees @List varchar(max) AS BEGIN SET NOCOUNT ON; SELECT value FROM STRING_SPLIT(@List, ','); END GO</code>openjson ()
<code class="language-sql">CREATE PROCEDURE dbo.DoSomethingWithEmployees @List varchar(max) AS BEGIN SET NOCOUNT ON; SELECT value FROM OPENJSON(CONCAT('["', REPLACE(STRING_ESCAPE(@List, 'JSON'), ',', '","'), '"]')) AS j; END GO</code>SQL Server 2008 (atau versi yang lebih tinggi)
objek pangkalan data SQL
<code class="language-sql">CREATE TYPE dbo.IDList AS TABLE ( ID INT ); GO CREATE PROCEDURE dbo.DoSomethingWithEmployees @List AS dbo.IDList READONLY AS BEGIN SET NOCOUNT ON; SELECT ID FROM @List; END GO</code>c# code
<code class="language-csharp">// 获取员工 ID int[] employeeIds = GetEmployeeIds(); // 创建 DataTable 并使用员工 ID 填充 DataTable tvp = new DataTable(); tvp.Columns.Add(new DataColumn("ID", typeof(int))); foreach (int id in employeeIds) tvp.Rows.Add(id); // 将 DataTable 作为参数添加 using (conn) { SqlCommand cmd = new SqlCommand("dbo.DoSomethingWithEmployees", conn); cmd.CommandType = CommandType.StoredProcedure; SqlParameter tvparam = cmd.Parameters.AddWithValue("@List", tvp); tvparam.SqlDbType = SqlDbType.Structured; tvparam.TypeName = "dbo.IDList"; // 执行查询 }</code>SQL Server 2005
fungsi sql
<code class="language-sql">CREATE FUNCTION dbo.SplitInts ( @List VARCHAR(MAX), @Delimiter VARCHAR(255) ) RETURNS TABLE AS RETURN ( SELECT Item = CONVERT(INT, Item) FROM ( SELECT Item = x.i.value('(./text())[1]', 'varchar(max)') FROM ( SELECT [XML] = CONVERT(XML, '<i>' + REPLACE(@List, @Delimiter, '</i><i>') + '</i>').query('.') ) AS a CROSS APPLY [XML].nodes('i') AS x(i) ) AS y WHERE Item IS NOT NULL ); GO</code>Prosedur Penyimpanan
<code class="language-sql">CREATE PROCEDURE dbo.DoSomethingWithEmployees @List VARCHAR(MAX) AS BEGIN SET NOCOUNT ON; SELECT EmployeeID = Item FROM dbo.SplitInts(@List, ','); END GO</code>
Atas ialah kandungan terperinci Bagaimana untuk lulus array ke prosedur yang disimpan SQL Server?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!