Showing posts with label transact-sql. Show all posts
Showing posts with label transact-sql. Show all posts

sqlshots: Add Leading Zeros

Typically in most cases you find yourself removing leading zeros but in this case I needed to add leading zeros to a column. 

Remove Leading Zeros

SELECT CAST(CAST(ColumnName AS INT) AS VARCHAR(10)) FROM TableName

Let's Pad the field

Since I needed 6 chars this will add 3 spaces to the front of the numbers

SELECT STR(ColumnName, 6) FROM TableName

Add Leading Zeros

Let's say we need to add zeros to an employee id, well this would be an easy way to accomplish it.

SELECT REPLACE(STR(ColumnName, 6), SPACE(1), '0') FROM TableName

SELECT SalesPersonID       ,REPLACE(STR(SalesPersonID, 6), SPACE(1), '0') AS PaddedSalesPID FROM   Sales.SalesPerson

Note: the SPACE(1) is equivalent to ' ' (That is a Tick Space Tick) So two Ticks with a space in between)

Update Table

UPDATE Sales.SalesPerson SET newSalesPID = REPLACE(STR(SalesPersonID, 6), SPACE(1), '0')

Posted via email from wetmatter nonsense

sqlshots: What version are you running?

1. This option is okay but not what I needed.

SELECT @@VERSION AS [Version Info]

2. This option is okay as well but does not indicate if it is 2000, 2005, 2008. Yeah it shows the product version number, but if you don't readily know it then you have to look it up.

SELECT SERVERPROPERTY('productversion')  AS [Version]         ,SERVERPROPERTY('edition')            AS [Edition]         ,SERVERPROPERTY('productlevel')     AS [Service Pack]

3. This option works okay but the you'll have issues with the Edition as the char length will differ

SELECT RIGHT(LEFT(@@VERSION,25),15)  AS [Product]        ,RIGHT(LEFT(@@VERSION,40),12) AS [Product Version]         ,LEFT(RIGHT(@@VERSION,65),17) AS [Edition]          ,SERVERPROPERTY('productlevel')  AS [Service Pack]

4. This is the winner for now (not great for version 6.5 & 7 as some additional char proceeds after due to the char length) 

SELECT RIGHT(LEFT(@@VERSION,25),15)    AS [Product]       ,RIGHT(LEFT(@@VERSION,40),12)   AS [Product Version]       ,SERVERPROPERTY('edition')      AS [Edition]       ,SERVERPROPERTY('productlevel') AS [Service Pack]

5. After some thought I like this route better

SELECT RIGHT(LEFT(@@VERSION,25),15)    AS [Product]    ,SERVERPROPERTY('productversion')   AS [Version]    ,SERVERPROPERTY('edition')          AS [Edition]    ,SERVERPROPERTY('productlevel')     AS [Service Pack]

I haven't tried this with any other version other than 2005, but I suspect 2000 & 2008 will work just fine. Earlier versions like 6.5 & 7 I am not sure of.

Posted via web from wetmatter nonsense