SQL优化技巧-批处理替代游标

时间:2023-12-16 12:27:14

通过MSSQL中的用户自定义表类型可以快速将需要处理的数据存储起来,生成新的临时表(这里使用变量表),然后根据表中字段进行批处理替代游标。

用户自定义表类型

 0 --创建用户自定义表类型
1 Create Type [dbo].[type_XXXTable] As Table(
[Item1] [Varchar](255) Null,
[Item2] [Varchar](255) Null,
[Item3] [Varchar](255) Null,
[Item4] [Varchar](255) Null,
[Item5] [Varchar](255) Null,
[Item6] [Varchar](255) Null,
[Item7] [Varchar](255) Null,
[Item8] [Varchar](255) Null,
[Item9] [Varchar](255) Null,
[Item10] [Varchar](255) Null,
[ItemInt1] [Int] Null,
[ItemInt2] [Int] Null,
[ItemInt3] [Int] Null,
[ItemInt4] [Int] Null,
[ItemInt5] [Int] Null,
[ItemFloat1] [Decimal](28, 8) Null,
[ItemFloat2] [Decimal](28, 8) Null,
[ItemFloat3] [Decimal](28, 8) Null,
[ItemFloat4] [Decimal](28, 8) Null,
[ItemFloat5] [Decimal](28, 8) Null,
[ItemDateTime1] [DateTime] Null,
[ItemDateTime2] [DateTime] Null
)
Go
0    --引用新数据表类型存储t_XXX表的FieldName1

1     Declare @XXX type_XXXTable
Insert Into @XXX(Item1) --Item1为刚才创建表类型的第一个字段
Select FIeldNmae1 From t_XXX
 --将游标动作改写为表处理
eg:
Select FieldName1 Into #t_XXX

 2018-07-14 14:34:38