我想要做這樣的事情:如何在SQL Server 2008中使用存儲過程中的if來比較兩個字符串?
declare @temp as varchar
set @temp='Measure'
if(@temp == 'Measure')
Select Measure from Measuretable
else
Select OtherMeasure from Measuretable
我想要做這樣的事情:如何在SQL Server 2008中使用存儲過程中的if來比較兩個字符串?
declare @temp as varchar
set @temp='Measure'
if(@temp == 'Measure')
Select Measure from Measuretable
else
Select OtherMeasure from Measuretable
兩件事情:
使用:
DECLARE @temp VARCHAR(10)
SET @temp = 'm'
IF @temp = 'm'
SELECT 'yes'
ELSE
SELECT 'no'
VARCHAR(10)
意味着VARCHAR可容納多達10個字符。行爲的更多例子 -
DECLARE @temp VARCHAR
SET @temp = 'm'
IF @temp = 'm'
SELECT 'yes'
ELSE
SELECT 'no'
...將返回 「是」
DECLARE @temp VARCHAR
SET @temp = 'mtest'
IF @temp = 'm'
SELECT 'yes'
ELSE
SELECT 'no'
...將返回 「不」。
declare @temp as varchar
set @temp='Measure'
if(@temp = 'Measure')
Select Measure from Measuretable
else
Select OtherMeasure from Measuretable
你想要的是一個SQL case語句。 這些形式可以是:
select case [expression or column]
when [value] then [result]
when [value2] then [result2]
else [value3] end
或:
select case
when [expression or column] = [value] then [result]
when [expression or column] = [value2] then [result2]
else [value3] end
在你的榜樣,你是後:
declare @temp as varchar(100)
set @temp='Measure'
select case @temp
when 'Measure' then Measure
else OtherMeasure end
from Measuretable
你也可以嘗試一下本作匹配的字符串。
DECLARE @temp1 VARCHAR(1000)
SET @temp1 = '<li>Error in connecting server.</li>'
DECLARE @temp2 VARCHAR(1000)
SET @temp2 = '<li>Error in connecting server. connection timeout.</li>'
IF @temp1 like '%Error in connecting server.%' OR @temp1 like '%Error in connecting server. connection timeout.%'
SELECT 'yes'
ELSE
SELECT 'no'
這對我不起作用我試過了。 – Vishal 2010-05-20 20:34:06
@VJ:這是因爲@temp VARCHAR意味着@temp將只存儲第一個字符;其餘的被截斷而沒有錯誤。 – 2010-05-20 20:38:41
@VJ引入一個參數,不要將值設置爲temp – Andrey 2010-05-20 20:54:57