代码改变世界

Sql用变量拼语句

2016-06-24 00:59  lijianhua  阅读(280)  评论(0编辑  收藏  举报
CREATE  PROC Test_GetCollegeInfo
@type int
AS
BEGIN
DECLARE  @where nvarchar(800),@v int,@sql nvarchar(max)
IF @type>2
 Begin
    SET @where='AND colleges.id='+cast(@type AS varchar(100))
 END
 ELSE
     BEGIN
         SET @where=''
     END
     
SET @sql='
SELECT * FROM collegeMajor 
INNER JOIN MajorsType ON  collegeMajor.majorType=MajorsType.id
INNER JOIN colleges ON colleges.id=collegeMajor.collageID
WHERE 1=1 '+@where  

EXEC (@sql)

End