且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 SQL (SQL Server) 将数字列表转换为(临时)表

更新时间:2023-02-03 12:54:55

我经常使用的解决方案...

A solution I use alot...

VARCHAR(MAX) 逗号分隔字符串的形式提供您的数字列表,然后使用人们在线编写的众多 dbo.fn_split() 函数之一.

Supply your list of numbers as a VARCHAR(MAX) comma delimeted string, then use one of the many dbo.fn_split() functions that people have written on line.

许多在线示例之一... SQL-User-Defined-Function-to-Parse-a-Delimited-Str

这些函数以一个字符串作为参数,并返回一个表.

These functions take a string as a parameter, and return a table.

然后你可以做这样的事情......

Then you can do things like...

INSERT INTO @temp SELECT * FROM dbo.split(@myList)

SELECT
  *
FROM
  myTable
INNER JOIN
  dbo.split(@myList) AS list
    ON list.id = myTable.id


另一种方法是查看表值参数.这些允许您将整个表作为参数传递给存储过程.如何取决于您使用的框架.您是否使用 .NET、Java、Ruby 等,您是如何与数据库通信的?

An alternative is to look into Table Valued Parameters. These allow you to pass a whole table in to a stored procedure as a parameter. How depends on the framework you're using. Are you in .NET, Java, Ruby, etc, and how are you communicating with the database?

一旦我们了解有关您的应用程序代码的更多详细信息,我们就可以向您展示用于使用表值参数的客户端代码和 SQL 存储过程模板.

Once we know more details about your applicaiton code we can show you both the client code, and the SQL stored procedure template, for using Table Valued Parameters.