简体   繁体   中英

SQL Server - Must declare the scalar variable

I am trying to declare these values and use execute them to get a specific values of an attribute in a table. However everytime I am time trying to set @test and @columnPeriod it gives me the error Must declare the scalar variable "@test" or Must declare the scalar variable "@columnPeriod"

DECLARE @columnPeriod VARCHAR(MAX), @test INT;
SET @test = 2015;
SET @columnPeriod = 'SELECT Period FROM Courses WHERE year = ' + @test + '';

You can't combine Strings and INTs

Try

SET @columnPeriod = 'SELECT Period FROM Courses WHERE year = ' + CONVERT(VARCHAR(12),@test) + ' Limit 1';

This will also limit your selection to ensure it is scalar

DECLARE @columnPeriod INT, @test varchar(4);
SET @test = '2015';
SET @columnPeriod = SELECT distinct Period FROM Courses WHERE year = ' + @test + '';

Assumptions being:

  • period only has ONE record with year 2015 if you have more than one but all the same "period" then distinct may be needed. If you have multiple, you can't do this as the record set returned has more than one row...
  • Year is a varchar datatype

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM