Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

SQL Server 2012: How to display the @Var result inside a Case statement with literals before and after the @Var

SQL Server 2012: how to display the @Var result inside a Case statement with literals before and after the @Var?

A simple query:

Declare @Var1 ...    
Declare @Var2....     

Select ....    
  CASE
     WHEN ...........    
      THEN 'Display this sentence ' + @Var1 +'followed by there words'    
      ELSE 'Display these other words  '  +@Var2  'followed by these other words'    
  END

The error message is

'Display this sentence' is not a declared variable.

I know it isn't! It should be a literal statement, only with the @Var1 result inside the literal statement.

What am I missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's nothing wrong the way you do the concatenation, i think the error is in the logic, do you have IF ELSE condition ? , maybe the error you encountered is on the two variables @var1 or @var2 , the reason why Display this sentence is not a declared variable is because that is the part of concatenation with the variables.

Tips:

  • Make sure that the declared variables @var1 and @var2 are inside the BEGIN and END of the condition, meaning the program reads your declaration before the CASE WHEN logic is being read.

  • If you are not sure with the logic, just declare your 2 variables at the top of the script to make sure that it is being read/declared.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...