简体   繁体   English

在这种情况下,如何编写SQL查询?

[英]How to write a SQL query for this case?

I need to write an SQL query where I can compare the results with the Excel cube. 我需要编写一个SQL查询,可以在其中将结果与Excel多维数据集进行比较。 For the particular table, it was updated for all contract numbers with only 5 digits where they added 0 in front of every five digit number. 对于特定的表,它仅对5位数字的所有合同编号进行了更新,在每5位数字的前面加了0。 And they left remaining number ie 6 digit numbers the same. 他们留下了剩余的数字,即6位数字相同。 But, this update is done in ETL package and the added 0 is transparent for me, ie I cannot see it in the table. 但是,此更新是在ETL程序包中完成的,添加的0对我来说是透明的,即我无法在表中看到它。

For example: for 90034 they added 0 in the beginning of the number ie 090034 but in the ETL package it appears to be 90034 in the table where 0 in front of 90034 is transparent. 例如:对于90034,他们在数字的开头添加了0,即090034,但在ETL程序包中,它在表中似乎是90034,其中90034前面的0是透明的。

And in Excel cube all the numbers are 6 digit numbers ex., 090034 在Excel多维数据集中,所有数字均为6位数字,例如090034

So, how can I write a SQL query to check if all the 5 digit numbers are been added with the 0 in the beginning and compare it with Excel cube? 因此,如何编写SQL查询来检查是否所有5位数字都在开头添加了0,并将其与Excel多维数据集进行比较?

Here's a snippet that will add leading zeroes to numbers of six or fewer digits: 这是一个片段,它将在6个或更少的数字前添加前导零:

 select   right('000000' + convert(varchar(6), MyID), 6)

That assumes that your column is called MyID and that it's a numeric data type already. 假定您的列称为MyID ,并且它已经是数字数据类型。 If it's already a string, you can try this: 如果已经是字符串,则可以尝试以下操作:

 select   right('000000' + ltrim(rtrim(MyID)), 6)

DISCLAIMER: This was done from memory and not tested. 免责声明:这是从内存中完成的,未经测试。

Its better for comparison purposes if the data in the database is stored as a varchar or nvarchar since it is clearly NOT a number or it would not have leading zeros. 如果数据库中的数据存储为varchar或nvarchar,则最好进行比较,因为它显然不是数字,也不会带有前导零。

If however you can't fix that and know the number of total character the string should have, this method would help. 但是,如果您不能解决该问题并且知道字符串应具有的总字符数,则此方法将有所帮助。

create table #test (myfield int)
insert into #test (myfield)
values(090034)
select * from #test
select Right('000000' + cast(myfield as varchar(6)) , 6) from #test

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

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