0

我需要列出所有的州。例如,我的状态表中的值是

01 - Tamilnadu
2 - Andhra
03 - MP
4 - Kerala

ETC。,,

我需要的是,如果之前的数字 - 是一位数字,那么我必须在后面加上零。例如,安得拉只有一位数字,我需要它作为 02 - 安得拉在选择期间返回原样的值。这是我的尝试,它有很多语法错误。你能请任何人帮我完成我的查询吗?

select [state],case(len(SUBSTRING([state],1,CHARINDEX('-', [state]+'-')-1)))
when  1 then
state = append zero in the state
when 2
state = leave value as it is
End
 from states where [state] is not null order by id desc;

谢谢

4

6 回答 6

0
Select replicate('0',2-len(stateId)) + cast(stateid as varchar) +'-' + state_name as  StateName
于 2013-08-13T09:10:16.077 回答
0

请看看这个。

SELECT state, 
CASE LENGTH(SUBSTRING_INDEX(state, '-', 1)) 
WHEN 1 
THEN CONCAT('0', state) 
END AS changedstate
FROM  states 
WHERE state ID NOT NULL 
ORDER BY id desc;

谢谢

于 2013-08-13T10:17:17.980 回答
0

如果您需要在执行操作时修复数字,则可能的解决方案SELECT

SELECT CASE WHEN state LIKE '[0-9] - %'
            THEN '0' + state
            ELSE state
       END state
  FROM states
 WHERE state IS NOT NULL
 ORDER BY Id DESC

样本输出:

状态
--------------
01 - 泰米尔纳德邦
02 - 安得拉
03 - 国会议员
04 - 喀拉拉邦

如果您需要更新这些值

UPDATE states
  SET state = '0' + state
 WHERE state LIKE '[0-9] - %'
于 2013-08-13T09:21:22.900 回答
0
select right('0'+state,2), statename
from states
于 2013-08-13T08:59:59.853 回答
0

尝试这个

Select Right('00'+cast(ColumnName As varchar),2)
from TableName

Select Right('00'+cast(state As varchar),2), StateName
from States where [state] is not null order by id desc;
于 2013-08-13T09:03:35.823 回答
0

一个简单的方法是连接大多数字符,然后使用右手。

像这样:

SELECT RIGHT('00' + CONVERT(VARCHAR,[state]), 2) + ' - ' + Name
FROM states
WHERE [state] IS NOT NULL
ORDER BY id DESC;

如果由于某种原因该[state]列包含所有数据(例如'1 - Tamilnadu'),那么您需要将其修改为如下所示:

SELECT RIGHT('00' + [state], LEN([state]))
FROM states
WHERE [state] IS NOT NULL

虽然最好将id分开。

于 2013-08-13T09:05:40.300 回答