简体   繁体   English

SQL(MS SQL 服务器)返回列值作为乘法的结果

[英]SQL (MS SQL Server) return column value as the result of the multiplication

I have a table in SQL that looks like the below:我在 SQL 中有一张表,如下所示: 在此处输入图像描述

table is like the below:表如下:

Partno   b5      b6      b7
A        3*38    4*38    5*38 
B        4*1100  8*1100  15*1100

Column b5,b6,b7 is currently nvarchar. b5、b6、b7 列当前是 nvarchar。 Can I check how to convert this column to int with the value of the multiplication?我可以检查如何使用乘法值将此列转换为 int 吗? Eg if column b5=3*38 I would like to return as 114 etc.例如,如果列 b5=3*38 我想返回 114 等。

Thank you very much.非常感谢。

With the following assumption, you can use split the query and do multiplication.有了以下假设,您可以使用拆分查询并进行乘法运算。

  • You are using sql server您正在使用 sql 服务器
  • There is only multiplication in the columns列中只有乘法
  • There is only two values in multiplication乘法中只有两个值
  • So ultimately, you have just a*b in the columns所以最终,你在列中只有a*b

You can use following query:您可以使用以下查询:

Select partno, 
       PARSENAME(REPLACE(b5,'*','.'),2) * PARSENAME(REPLACE(b5,'*','.'),1) as b5_res,
       PARSENAME(REPLACE(b6,'*','.'),2) * PARSENAME(REPLACE(b6,'*','.'),1) as b6_res,
       PARSENAME(REPLACE(b7,'*','.'),2) * PARSENAME(REPLACE(b7,'*','.'),1) as b7_res
From your_table t

Given the structure of the data, you could use simple string operations:给定数据的结构,您可以使用简单的字符串操作:

select t.*,
       multiple * try_convert(int, left(b4, charindex('*', b4) - 1)),
       multiple * try_convert(int, left(b5, charindex('*', b5) - 1)),
       multiple * try_convert(int, left(b6, charindex('*', b6) - 1))
from t;

Here is a db<>fiddle. 是一个 db<>fiddle。

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

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