How To Locate and Take Substrings with CHARINDEX() and SUBSTRING() Functions?
Submitted by: AdministratorTransact-SQL is not a language designed for manipulating strings, but it does have two simple functions to locate and take substrings: CHARINDEX() and SUBSTRING(). The tutorial exercise below assumes two given strings: 'Pages: 18' and 'Words: 3240'. The objective is to calculate the number of words per page. Read the script below to see how this is done by using CHARINDEX() and SUBSTRING() functions:
DECLARE @sPages VARCHAR(40), @sWords VARCHAR(40);
SET @sPages = 'Pages: 18';
SET @sWords = 'Words: 3240';
SET @sPages = SUBSTRING(@sPages, CHARINDEX(':', @sPages)+1, 20);
SET @sWords = SUBSTRING(@sWords, CHARINDEX(':', @sWords)+1, 20);
PRINT 'Number of words per page: '
+ CONVERT(VARCHAR(20), CONVERT(INT, @sWords)/CONVERT(INT, @sPages));
GO
Number of words per page: 180
If you are a PHP developer, you can get this done in a much quick way.
Submitted by: Administrator
DECLARE @sPages VARCHAR(40), @sWords VARCHAR(40);
SET @sPages = 'Pages: 18';
SET @sWords = 'Words: 3240';
SET @sPages = SUBSTRING(@sPages, CHARINDEX(':', @sPages)+1, 20);
SET @sWords = SUBSTRING(@sWords, CHARINDEX(':', @sWords)+1, 20);
PRINT 'Number of words per page: '
+ CONVERT(VARCHAR(20), CONVERT(INT, @sWords)/CONVERT(INT, @sPages));
GO
Number of words per page: 180
If you are a PHP developer, you can get this done in a much quick way.
Submitted by: Administrator
Read Online MS SQL Server Job Interview Questions And Answers
Top MS SQL Server Questions
☺ | What Happens If You Insert a Duplicate Key for the Primary Key Column in MS SQL Server? |
☺ | How To Execute the Cursor Queries with "OPEN" Statements? |
☺ | What Happens If Strings Are Casted into Wrong Code Pages in MS SQL Server? |
☺ | How To Declare and Use Cursor Variables? |
☺ | PHP MSSQL - How To Display a Past Time in Days, Hours and Minutes? |
Top Databases Programming Categories
☺ | RDBMS Interview Questions. |
☺ | SQL Interview Questions. |
☺ | SSRS Interview Questions. |
☺ | Database Administrator (DBA) Interview Questions. |
☺ | Sybase Interview Questions. |