最近在做一個能源監控的項目,因為用到從表里獲取數據后得知數據存在哪一個表里后,再獲取那個表的數據,所以就遇到了一個表名不固定的情況,一開始的方式,是我分兩條sql語句來執行:
1.第一條sql 是通過條件來查詢數據 ex:tblName(這個數據就是要去調用數據的表名)
select HisTblName,HisFldName from TYcYt where StationId=1 and YcCommDevId=1 and CommDevYcOrder=170
2.第二條語句就是執行select*from tblName........等一些列的語句動作。
select Value1 from THisSampleFiveMinute_1 where SampleTime=(select max(SampleTime) from THisSampleFiveMinute_1 where cast(SampleTime as date)='2017/3/28 0:00:00')
那么有沒有什么方法,可是一句sql語句來實現呢,思路是將第一次查詢出來的數據做表名,再次進行查詢等動作,答案是有的,那個就是要用的變量的聲明、變量的賦值、動態SQL(Exec)這些語句:
關於變量的聲明、變量的賦值,可以參看之前寫的關於select賦值的文章,這里重點講下動態SQL(Exec)這一語句的使用方法:
字段名,表名,數據庫名之類作為變量時,必須用動態SQL
declare @fname varchar(20)
set @fname = 'FiledName'
Select @fname from tableName -- 錯誤!不會提示錯誤,但結果為固定值FiledName,並非所要。
Exec('select ' + @fname + ' from tableName') -- 正確!請注意加號前后的單引號的邊上加空格
declare @fldName varchar(32) set @fldName=(select HisFldName from TYcYt where StationId=1 and YcCommDevId=1 and CommDevYcOrder=170) declare @tblName varchar(32) set @tblName=(select HisTblName from TYcYt where StationId=1 and YcCommDevId=1 and CommDevYcOrder=170) Exec ( 'select '+@fldName+' from '+@tblName +' where SampleTime=(select max(SampleTime) from '+@tblName +' where cast(SampleTime as date)=''2017/3/29 0:00:00'')' )
這里有一個問題,就是如果sql當中時間是變化的怎么辦,想普通sql一樣把時間單獨獨立出來就可以嗎?其實是不行的,再動態SQL(Exec)中,必須將時間聲明一個變量才可以,不然就會報錯:
declare @fldName varchar(32) set @fldName=(select HisFldName from TYcYt where StationId=1 and YcCommDevId=1 and CommDevYcOrder=170) declare @tblName varchar(32) set @tblName=(select HisTblName from TYcYt where StationId=1 and YcCommDevId=1 and CommDevYcOrder=170) declare @dt datetime set @dt='2017/3/29 0:00:00' Exec ( 'select '+@fldName+' from '+@tblName +' where SampleTime=(select max(SampleTime) from '+@tblName +' where cast(SampleTime as date)='''+@dt+''')' )
至此,大功告成-----姜彥 20170331