进行数字比较的强制转换/过滤字符串

时间:2018-07-19 03:52:44

标签: sql sql-server

Table Values
Id     Code       FileNum     LowLim     HighLim
------------------------------------------------

A     N18:35        18         30         40
B     N20:20        18         30         40

“代码”列将以N [filenum]:[value]的格式存储代码。 如何有效格式化/拆分这些代码以进行数字比较?

-想将代码的[fileNum]部分与FileNum比较

-想检查代码的[value]部分是否在LowLim和HighLim范围内。

预期结果将是

Id

----
A     (because A's code [filenum] 18 matches the fileNum 18 and [value] 35 is within the range of the limits (30..40), 

B不会出现在结果中,因为即使[value] 20落在(30..40)范围内,代码的[filenum] 20与它的fileNum 18也不匹配

我尝试使用left,right和replace,但是没有一个可以称为优雅解决方案。谢谢。

3 个答案:

答案 0 :(得分:1)

只要Code的格式为Nx:y,其中x和y可以是任意长度的整数,那么这是一种可行的方法。因此,N18:35将起作用,但N1289:34872也将起作用。

示例DDL和DML语句:

DECLARE @tbl TABLE (ID CHAR(1), Code VARCHAR(25), 
    FileNum INT, LowLim INT, HighLim INT)
INSERT INTO @tbl VALUES 
('A', 'N18:35', 18, 30, 40),
('B', 'N20:20', 18, 30, 40),
('C', 'N1289:34872', 1289, 34000, 35000)

嵌套的CTE将代码值拆分为FileNumPart和LimitPart值,首先删除“ N”,然后使用CHARINDEX拆分冒号的任何一侧,最后使用条件选择语句:

;WITH cte AS (
    SELECT ID, REPLACE(Code, 'N', '') AS Code
    FROM @tbl
),
cte2 AS (
    SELECT ID, SUBSTRING(Code, 1, CHARINDEX(':', Code) - 1) AS FileNumPart
    ,SUBSTRING(Code, CHARINDEX(':', Code) + 1, LEN(Code) - CHARINDEX(':', Code)) AS LimitPart
    FROM cte
)
SELECT t.ID
FROM cte2
INNER JOIN @tbl t ON cte2.ID = t.ID
WHERE t.FileNum = cte2.FileNumPart AND cte2.LimitPart BETWEEN t.LowLim AND t.HighLim

答案 1 :(得分:0)

尝试一下

select * from val where substring(code, 2, CHARINDEX(':', code) - 2) = FileNum

答案 2 :(得分:0)

我们假设表名称为 public void PickImage(View view) { AlertDialog.Builder builder = new AlertDialog.Builder(this); final String[] weightUnitOptions = {"Camera", "Gallery"}; builder.setTitle("Pick Image from") .setItems(weightUnitOptions, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (which == 0) { Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(takePicture, 0); } else { Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(pickPhoto , 1); } } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); AlertDialog dialog = builder.create(); dialog.show(); } protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { super.onActivityResult(requestCode, resultCode, imageReturnedIntent); if (resultCode != RESULT_CANCELED) { if (requestCode == 0) { Uri selectedImage = imageReturnedIntent.getData(); imageView.setImageURI(selectedImage); } else if (requestCode == 1) { Uri selectedImage = imageReturnedIntent.getData(); imageView.setImageURI(selectedImage); } else { super.onActivityResult(requestCode, resultCode, imageReturnedIntent); } } }

Test