通過一個很實用的例子讓你學會T-SQL編程的基本語法和思想


例子需求:把Execl中的三級分類(列別的三級聯動)數據導入到數據庫中。

     Excel表中數據的顯示格式:

     圖1

     數據庫中表的顯示格式:

     圖2

首先把Excell表中的數據導入到數據庫的臨時表中(右鍵 點擊數據庫->任務->導入數據,根據自己的數據源類型就能導入到數據庫了),然后通過TSQ編程把臨時表中的數據導入分類表。

(1)再導入的過程中,若是用到數組會簡單許多,但是TSQ編程中沒有數組,我們可以寫一個方法來模仿數組的功能,同時了解一下T—SQL編程的基本語法:

      我們使用數組是為了存儲數據和遍歷數據,存儲數據用一個有規則的字符串,如“12,23,45,67”,這樣兩個逗號之間的內容可以看成一個數組的元素,也可以用“、”,“|”等其他符號分割,為了邏輯的簡便,下面的例子用逗號分割;接下來是遍歷數組,我們在遍歷高級數組的時候用到兩份方法,一個是知道這個數組的長度,一個是能根據指定的索引獲取數組的元素值;所以我們就創建這兩個方法Get_Str_ArrayLength()和Get_StrArrayIndex()來獲取數組的長度和指定索引的值;

下面的是創建一個標量函數,創建過的函數在同一個數據庫中能多次使用,

use Test
----獲取字符串中元素的個數
go   --go表示一批T-SQL命令語句的開始和結束
create function Get_StrArrayLength   --創建標量函數
(
@str nvarchar(1024)    ---函數的參數名稱和類型
)
returns int   ---函數的返回類型
as
begin         ---beng和end 相當於C#中的{}
 declare @location int,@start int,@length int        --通過declare來聲明參數
  set @str=ltrim(rtrim(@str))           --通過set和select給參數賦值,set一次只能給一個參數賦值,select一次可以給多個參數賦值
  set @location=charindex(',',@str)
  set @length=1
   while @location<>0            --T-SQL中沒有for循環只能通過while循環來模擬for循環
     begin
      set @start=@location+1
      set @location=charindex(',',@str,@start)
      set @length=@length+1
     end
   return @length   --函數的返回值,即返回這個數組的長度
 end
 
go

上面這個例子有一個比較重要的系統自帶的處理字符串的函數charindex(str1,str,startIndex),即獲取str1在str中其實位置的索引,startIndex可為空為空時,起始位置為1,T-SQL的索引是從1開始的不像C#是從0開始的。
獲取指定索引的值還需要一個比較重要的字符串處理函數substring(str,startIndex,num)。看一下下面的例子,熟悉一下這兩個函數:

declare @str nvarchar(100),@str1 nvarchar(100)
set @str='123sdfs53refsdgh'
set @str1=CHARINDEX('3s',@str)
print @str1  --3
set @str1=SUBSTRING(@str,2,5)
print @str1 --23sdf

 獲取指定索引的元素值

go
create function Get_StrArrayIndex
(
@str nvarchar(500),
@index int --3
)
returns nvarchar(100)
as 
begin
 declare @location int
 declare @start int
 declare @i int
 set @str=ltrim(rtrim(@str))
 set @start=1
 set @i=1
 set @location=charindex(',',@str) 
 while @i<@index
   begin
    set @start=@location+1
    set @location=charindex(',',@str,@start)
    set @i=@i+1
   end
 return substring(@str,@start,@location-@start)
end
go

有了上面這兩個標量函數,我們在以后的T-SQl編程中就可以像使用系統函數一樣使用,下面步入正題把臨時表中的數據導入到三級分類表,方法有很多,這里使用游標,因為游標相對好理解點,使用游標比較消耗性能,所以一般情況下不用,在萬般無奈的情況下才用。我們就先大概說一下游標的原理:游標就是能夠把數據庫中表的內容一行一行的拿出來處理。想進一步了解游標,網上有篇不錯的文章大家可以參考一下:http://www.cnblogs.com/moss_tan_jun/archive/2011/11/26/2263988.html

下面看例子:area為臨時表數據相當於圖1 ,AreaType為要導入進去的表;

--聲明參數
declare @step1 nvarchar(50),@step2 nvarchar(50),@step3 nvarchar(3000),@tempParentId int,@tempStep int
declare import_cursor cursor for  --聲明游標
select step1,step2,step3 from area  --游標所要遍歷的一行一行的數據集
open import_cursor                  --打開游標
fetch next from import_cursor into @step1,@step2,@step3  --把遍歷結果賦值給這三個參數
while (@@FETCH_STATUS=0)   --通過@@FETCH_STATUS=0判斷游標是否遍歷完
begin
    --第一級插入
    select @tempParentId=0,@tempStep=1
    --判斷一下一級目錄是否已經插入了
    select @tempParentId=Id from dbo.AreaType where name=@step1
    if(@tempParentId<1)--一級目錄表中還沒有插入
    begin
        insert into dbo.areaType values(@step1,@tempParentId,@tempStep,0,GETDATE())
        select @tempParentId=Id from dbo.AreaType where name=@step1
            --第二級插入
            select @tempStep=2
            insert into dbo.areaType values(@step2,@tempParentId,@tempStep,0,GETDATE())
                --第三級插入
               set @tempStep=3
               select @tempParentId=Id from dbo.AreaType where name=@step2
               declare @i int ,@step3Split nvarchar(100)
               select @tempStep=3,@i=1,@step3Split=''
               while(@i<dbo.Get_StrArrayLength(@step3))
                   begin
                   select @step3Split=dbo.Get_StrArrayIndex(@step3,@i);
                   insert into dbo.areaType values(@step3Split,@tempParentId,@tempStep,0,GETDATE());
                   set @i=@i+1;
                   end
    end
    else --一級目錄已經插入過了
    begin
    --第二級插入
            select @tempStep=2
            insert into dbo.areaType values(@step2,@tempParentId,@tempStep,0,GETDATE())
                --第三級插入
               set @tempStep=3
               select @tempParentId=Id from dbo.AreaType where name=@step2
               declare @j int ,@step3Split1 nvarchar(100)
               select @tempStep=3,@j=1,@step3Split1=''
                   while(@j<dbo.Get_StrArrayLength(@step3))
                   begin
                   select @step3Split1=dbo.Get_StrArrayIndex(@step3,@j);
                   insert into dbo.areaType values(@step3Split1,@tempParentId,@tempStep,0,GETDATE());
                   set @j=@j+1;
                   end
    end
fetch next from import_cursor into @step1,@step2,@step3           
end
close import_cursor  --關閉游標
deallocate import_cursor  --釋放游標的資源

里面用到了我們上面定義的兩個標量函數Get_Str_ArrayLength()和Get_StrArrayIndex(),主要是為了拆分第三級目錄進行插入,里面的邏輯很簡單,就不在此說了。

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM