AlphaPress Publishing
P.O. Box 5942 Albany, NY 12205
Tel: 518-250-3890
Email: alphapress@hotmail.com  


  
Click to buy this book from Amazon

Section Menu 

News

Pindaro is now working on a comprehensive book on SQL Server 2014.  For any comments you can email the author at alphapress@hotmail.com.

  

 

 

Use the instr() function to find the position of any character in a string

To contact the author click here

This article is from the book "Access 2007 Pure SQL

To download the sample database click here


Use the instr() function to find the position of a character in a string evaluating from the beginning of a string

Find the number of characters occurring before the "-" character in the SKUs field

Discussion:

In business, we use stock keeping unit codes (SKU) to assign a unique code to products.  In our products table, we do have an SKU field.  This code consists of some letters and a hyphen followed by some numbers like PDKLS-3483.  The letter part of the code before the hyphen signifies some larger category, and we might be required to create a report listing only the letter part of the SKU codes.  Our problem is that the number of letters in the SKU code might not always be the same.  At least this is what happened in my own experience.  So, how can we get the string part of the SKU independent of the number of characters it consists of?  To complete this task effectively, we first use the instr() function to determine the position of the hyphen in the string (PDKLS-3483).  Its general syntax appears below: 

instr(starting character, field, character to find) 

In this example, we use inStr(1,sku,"-") to look for the "-" character in the SKU field starting from the first character.

Code:

SELECT productid, productname, sku, InStr(1,sku,"-") AS PartSKU

FROM Products

 

Result: