最近裝了VS2010嘗鮮。在Win7下速度明顯快了很多。順便裝了Microsoft sql server 2008 R2,在看SQL 2008對T-SQL語法的增強的時候注意到了一個表變量作為參數傳遞的新語法覺得很不錯。
首先建立一張測試表:
CREATE TABLE [dbo].[us](
[id] [int] IDENTITY(1,1) NOT NULL,
[name] [varchar](50) NULL,
[pass] [varchar](50) NULL,
CONSTRAINT [PK_us] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
定義一個自定義表類型:
CREATE TYPE [dbo].[UsTable] AS TABLE(
[id] [int] IDENTITY(1,1) NOT NULL,
[NAME] [varchar](50) NULL
)
然後我們寫一個存儲過程來傳遞這個類型,這裡我們模擬用戶批量添加默認密碼為123
CREATE PROC [dbo].[addus]
@tab [UsTable] READONLY
AS
BEGIN
INSERT INTO us(name,pass) SELECT name,'123' FROM @tab
END
測試一下:
–-定義一個自定義表類型的變量
DECLARE @us UsTable
--插入模擬數據
INSERT INTO @us (name) VALUES ('dc')
INSERT INTO @us (name) VALUES ('ada')
INSERT INTO @us (name) VALUES ('dacey')
--執行存儲過程
EXEC dbo.addus @tab = @us
查詢us表看下是否都插入進去了:
1 dc 123
2 ada 123
3 dacey 123
關鍵詞:SQL 參數 表 變量