如何在sql字符串值中显示参数

时间:2012-03-08 15:18:09

标签: sql sql-server tsql

我可以在SQL

中执行以下脚本吗?
Select Year as ' years between ' +  @StartYear + '-' +  @EndYear + ' value ' 
from tblYears
where Year Between @StartYear and @EndYear

2 个答案:

答案 0 :(得分:3)

您的as已切换。这个名字最后是

Select 'years between ' +  @StartYear + '-' +  @EndYear + ' value ' AS Year
from tblYears
where Year Between @StartYear and @EndYear

现在@StartYear和@EndYear可能不是char / varchar / nchar / nvarchar所以你需要转换它们。我假设你的年份是一个4位整数。如果不是,你需要调整它。

Select 'years between ' +  convert(char(4), @StartYear) + '-' +  convert(char(4), @EndYear) + ' value ' AS Year
from tblYears
where Year Between @StartYear and @EndYear

答案 1 :(得分:0)

我相信你想要的是这样的,你将所选行的值插入到最终输出中?

SELECT CONVERT(CHAR(4), Year) + ' year is between ' 
    + CONVERT((CHAR(4),@StartYear) +'-'+ CONVERT((CHAR(4),@EndYear) + ' values.' 
FROM tblYears
WHERE Year BETWEEN @StartYear AND @EndYear

否则,您甚至不需要FROM或WHERE,因为您将一遍又一遍地打印相同的东西。然后,我建议:

SELECT ' years between ' + CONVERT((CHAR(4),@StartYear) + '-' 
    + CONVERT((CHAR(4),@EndYear) + ' value'