Friday, December 02, 2005

An Experiment (with special bonus GARBAGE SQL script)

Gonna try posting some source code that I wrote for a friend today. It's really horrible and I'm embarrased to be posting it.

Here goes:



SET nocount ON

declare @foo varchar(10)

SET @foo = 'abc123'

CREATE TABLE #tmpLetters (
letter char)

INSERT INTO #tmpLetters (letter) values ('a')
INSERT INTO #tmpLetters (letter) values ('b')
INSERT INTO #tmpLetters (letter) values ('c')
INSERT INTO #tmpLetters (letter) values ('d')
INSERT INTO #tmpLetters (letter) values ('e')
INSERT INTO #tmpLetters (letter) values ('f')
INSERT INTO #tmpLetters (letter) values ('g')
INSERT INTO #tmpLetters (letter) values ('h')
INSERT INTO #tmpLetters (letter) values ('i')
INSERT INTO #tmpLetters (letter) values ('j')
INSERT INTO #tmpLetters (letter) values ('k')
INSERT INTO #tmpLetters (letter) values ('l')
INSERT INTO #tmpLetters (letter) values ('m')
INSERT INTO #tmpLetters (letter) values ('n')
INSERT INTO #tmpLetters (letter) values ('o')
INSERT INTO #tmpLetters (letter) values ('p')
INSERT INTO #tmpLetters (letter) values ('q')
INSERT INTO #tmpLetters (letter) values ('r')
INSERT INTO #tmpLetters (letter) values ('s')
INSERT INTO #tmpLetters (letter) values ('t')
INSERT INTO #tmpLetters (letter) values ('u')
INSERT INTO #tmpLetters (letter) values ('v')
INSERT INTO #tmpLetters (letter) values ('w')
INSERT INTO #tmpLetters (letter) values ('x')
INSERT INTO #tmpLetters (letter) values ('y')
INSERT INTO #tmpLetters (letter) values ('z')


declare lc cursor fast_forward
FOR
SELECT * FROM #tmpLetters

declare @letter char
declare @hasalpha bit
SET @hasalpha = 0

open lc

fetch next FROM lc INTO @letter

while @@fetch_status = 0
begin
IF (CHARINDEX(@letter,@foo) <> 0)
begin
SET @hasalpha = 1
end
fetch next FROM lc INTO @letter
end

close lc
deallocate lc

DROP TABLE #tmpLetters

IF @hasalpha = 1
begin
print 'Has Alpha Characters'
end
else
begin
print 'No Alpha Characters'
end

SET nocount off

Don't you feel just a little bit sick? A temp table AND a cursor to find out if a varchar contains alpha characters...

Vomjom claims to have a one-liner that will do this. I'll post it when he gives it to me (Mark: I think we have a peed-on doctor's note situation here...)

[EDIT]

And, we killed the fly with the shotgun once again. Here's the quick way:


declare @foo varchar(10)
set @foo = 'abc123'
IF(@foo LIKE '%[a-z]%')
BEGIN
print 'Has Alphas'
END
ELSE
BEGIN
print 'No Alphas'
END


Live and learn, I suppose...

0 Comments:

Post a Comment

<< Home