gpt4 book ai didi

sql-server - 将 CSV 字符串与 IN 运算符一起使用时出错

转载 作者:行者123 更新时间:2023-12-03 16:28:44 25 4
gpt4 key购买 nike

当我运行下面的代码时

declare @aaa nvarchar(10)
set @aaa='1,2,3'
Select * from Customer where CustomerId in (convert(nvarchar,@aaa,10))

我收到这个错误

Msg 8114, Level 16, State 5, Line 3
Error converting data type nvarchar to bigint.

求助

最佳答案

您不能将 IN 与 cvs 字符串一起使用。如果您有 Sql Server 2008,则可以使用表值参数(SQL Server 2008 中的新参数)。通过创建实际的表参数类型来设置它:

CREATE TYPE IntTableType AS TABLE (ID bigint PRIMARY KEY)

您的程序将是:

Create Procedure up_TEST
@Ids IntTableType READONLY
AS

SELECT *
from Customer where CustomerId in (SELECT ID FROM @Ids)

RETURN 0
GO

如果不能使用表值参数,参见:"Arrays and Lists in SQL Server 2008 Using Table-Valued Parameters" by Erland Sommarskog , 那么在SQL Server中拆分字符串的方法有很多种。本文介绍了几乎所有方法的优缺点:

"Arrays and Lists in SQL Server 2005 and Beyond, When Table Value Parameters Do Not Cut it" by Erland Sommarskog

您需要创建一个拆分函数。这是拆分函数的用法:

SELECT
*
FROM YourTable y
INNER JOIN dbo.yourSplitFunction(@Parameter) s ON y.ID=s.Value

I prefer the number table approach to split a string in TSQL但是在 SQL Server 中拆分字符串的方法有很多种,请参阅前面的链接,其中解释了每种方法的优缺点。

要使 Numbers Table 方法起作用,您需要执行一次时间表设置,这将创建一个表 Numbers,其中包含从 1 到 10,000 的行:

SELECT TOP 10000 IDENTITY(int,1,1) AS Number
INTO Numbers
FROM sys.objects s1
CROSS JOIN sys.objects s2
ALTER TABLE Numbers ADD CONSTRAINT PK_Numbers PRIMARY KEY CLUSTERED (Number)

设置 Numbers 表后,创建此拆分函数:

CREATE FUNCTION [dbo].[FN_ListToTable]
(
@SplitOn char(1) --REQUIRED, the character to split the @List string on
,@List varchar(8000)--REQUIRED, the list to split apart
)
RETURNS TABLE
AS
RETURN
(

----------------
--SINGLE QUERY-- --this will not return empty rows
----------------
SELECT
ListValue
FROM (SELECT
LTRIM(RTRIM(SUBSTRING(List2, number+1, CHARINDEX(@SplitOn, List2, number+1)-number - 1))) AS ListValue
FROM (
SELECT @SplitOn + @List + @SplitOn AS List2
) AS dt
INNER JOIN Numbers n ON n.Number < LEN(dt.List2)
WHERE SUBSTRING(List2, number, 1) = @SplitOn
) dt2
WHERE ListValue IS NOT NULL AND ListValue!=''

);
GO

您现在可以轻松拆分 CSV 字符串并在查询中使用它:

declare @aaa nvarchar(10)
set @aaa='1,2,3'
Select * from Customer where CustomerId in (SELECT ListValue FROM dbo.FN_ListToTable(',',@aaa))

关于sql-server - 将 CSV 字符串与 IN 运算符一起使用时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3449183/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com