简体   繁体   English

使用IN关键字在SQL查询中无法将参数值从字符串转换为Int64

[英]Failed to convert parameter value from a String to a Int64 in SQL query with IN keyword

I have following table structures. 我有以下表结构。

  **Table_A**
        A_Id(BigInt)    Category_Ids(varchar(50))
        1                        1,2,3
        2                         2,3

    **Table_B**
        B_Id(BigInt)    C_Id(Bigint)    Name(varchar(50))
        1                         2              A
        2                         1              C
        3                         3              B

First Query: In this query want to get the record where A_Id=1. 第一个查询:在此查询中要获取其中A_Id = 1的记录。 I have executed following code. 我已经执行了以下代码。 Select [Category_Ids] from Table_A where A_Id=1 This returns the data table with single column and single row with values “1, 2, 3” Assume that above query fills the data into the A_datatable. 从Table_A中选择[Category_Ids],其中A_Id = 1这将返回具有单列和单行的数据表,其值分别为“ 1、2、3”。假设以上查询将数据填充到A_datatable中。 I get the string from following code. 我从下面的代码中获取字符串。 String ids = A_datatable.column[0][“Category_Ids”]; 字符串ID = A_datatable.column [0] [“ Category_Ids”];

Second Query: Now, I have to fetch the values from Table_B where C_Id in (1, 2, 3). 第二个查询:现在,我必须从(1、2、3)中C_Id的Table_B中获取值。 I have executed following code and passed the string value to following query. 我已执行以下代码,并将字符串值传递给以下查询。 Select * from Table_B where C_Id in (ids) When I execute above query getting the error, failed to convert parameter value from a String to a Int64. 从Table_B中选择*,其中(ids)中的C_Id在执行上述查询时遇到错误, 无法将参数值从String转换为Int64。

You can actually do it in a single query. 实际上,您可以在单个查询中执行此操作。

SELECT  b.*
FROM    Table_A a
        INNER JOIN Table_B b
            ON ',' + a.Category_IDs + ',' LIKE '%,' + CAST(C_ID AS VARCHAR(10)) + ',%'
WHERE   a.A_ID = 1

Caveat: This query is an index-killer. 警告:此查询是索引杀手。 You should have properly normalize your tables. 您应该已经正确规范化了您的表。

UPDATE 1 更新1

Suggested Schema Design, 建议的架构设计

Table_A 表_A

  • A_ID 援助
  • Category_ID Category_ID

Table_C 表_C

  • B_ID 出价
  • C_ID C_ID
  • Name 名称

Records 记录

Table_A 表_A

A_ID    Category_ID
1       1
1       2
1       3
2       4
2       5

Table_B 表_B

B_Id    C_Id    Name
1       2       A
2       1       C
3       3       B

You can use a string splitter function like the one described here http://www.sqlservercentral.com/articles/Tally+Table/72993/ 您可以使用字符串拆分器功能,如此处所述http://www.sqlservercentral.com/articles/Tally+Table/72993/

scroll down to the 'CREATE FUNCTION' script and run it to create your function, then you can split the comma separate string for use in your 'where in' clause 向下滚动到“ CREATE FUNCTION”脚本并运行它以创建函数,然后可以将逗号分隔的字符串拆分以用于“ where in”子句中

select * from Table_B 从Table_B中选择*
where C_Id in (select item from dbo.DelimitedSplit8K(IDS,',')) 其中的C_Id(从dbo.DelimitedSplit8K(IDS,',')中选择项)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM