2011-03-01 135 views
0

如果我想在一個變量中存儲多個值,我怎麼能在存儲過程中做到這一點?如何在存儲過程中存儲多個值?

我的意思是,我們在正常節目陣列概念做我們在

+0

你是指[csv](http://en.wikipedia.org/wiki/Comma-separated_values)之類的東西嗎? – 2011-03-01 10:58:11

+0

是的,你做它叫做表 – Luis 2011-03-01 10:58:56

+0

正如路易斯指出的,數據庫使用表... – MatBailie 2011-03-01 11:13:06

回答

2

如果存儲只是程序的範圍內所需的存儲過程類似的東西,那麼臨時表,在那裏來救你。

2

根據您的特定數據庫,有幾個選項可用。

在SQL Server中,你可以定義

  • 一個臨時表只是你的連接(CREATE TABLE #YourTable(.....)
  • 全局臨時表可見於任何連接(CREATE TABLE ##YourTable(.....)
  • 表變量(DECLARE @YourVariable TABLE (.....)
0

您可以創建一個完整表的變量。這裏是一個代碼示例:

USE AdventureWorks2008R2; 
GO 
DECLARE @MyTableVar table(
    EmpID int NOT NULL, 
    OldVacationHours int, 
    NewVacationHours int, 
    ModifiedDate datetime); 
UPDATE TOP (10) HumanResources.Employee 
SET VacationHours = VacationHours * 1.25, 
    ModifiedDate = GETDATE() 
OUTPUT inserted.BusinessEntityID, 
     deleted.VacationHours, 
     inserted.VacationHours, 
     inserted.ModifiedDate 
INTO @MyTableVar; 
--Display the result set of the table variable. 
SELECT EmpID, OldVacationHours, NewVacationHours, ModifiedDate 
FROM @MyTableVar; 
GO 
--Display the result set of the table. 
SELECT TOP (10) BusinessEntityID, VacationHours, ModifiedDate 
FROM HumanResources.Employee; 
GO 

正如你所看到的,你聲明它就像一個普通表一樣。在程序結束時它會超出範圍。

這些被稱爲表變量。也有臨時表,你可以創建,在大致相同的方式工作,希望你與聲明它們:create table #tmp (Col1 int, Col2 int);

有一個很好的SO張貼關於這兩個位置之間的區別:What's the difference between a temp table and table variable in SQL Server?

回到你原來的問題:你可以創建一個表變量並假裝它是一個數組(好吧!)。你只需要考慮SQL的數組函數,所以你可以使用WHERE子句而不是.Find

相關問題