[英]What is best alternate for cursor in T-SQL?
I have a design concern which I need to implement without using cursor. 我有一个设计问题,我需要在不使用游标的情况下实现。
There is source table 'A' which will have all column in varchar
data type. 有一个源表“ A”,它将具有
varchar
数据类型的所有列。 I want to iterate over them and convert each column to destination table data type and if conversion/parsing fails, I need to log that row in extra error table. 我想遍历它们并将每一列转换为目标表数据类型,如果转换/解析失败,则需要将该行记录在额外的错误表中。
Any suggestions to go ahead will be helpful. 提出任何建议都将有所帮助。
In SQL Server, you would use try_convert()
: 在SQL Server中,您可以使用
try_convert()
:
insert into t2 ( . . . )
select . . .
from (select try_convert(?, col1) as col1,
try_convert(?, col1) as col2,
from staging_t
) t
where col1 is not null and col2 is not null and . . .;
Then run a second query to get the rows where the value is NULL
. 然后运行第二个查询以获取值为
NULL
的行。
If NULL
is a permitted value in the staging column, then this is a bit more complex: 如果在登台列中允许使用
NULL
值,则情况会有些复杂:
insert into t2 ( . . . )
select new_col1, new_col2, . . .
from (select try_convert(?, col1) as new_col1, col1,
try_convert(?, col1) as new_col2, col2,
from staging_t
) t
where (new_col1 is not null or col1 is null) and
(new_col2 is not null or col2 is null) and
. . .;
In Sql Server 2012 and up: each of these will return null
when the conversion fails instead of an error. 在Sql Server 2012及更高版本中:当转换失败而不是错误时,这些参数中的每一个都将返回
null
。
Example of all varcharcol
that would fail conversion to int: 所有将无法转换为int的
varcharcol
示例:
select id, varcharcol
from a
where try_convert(int,varcharcol) is null
Use Above Query Using User Define Table Type 使用以上查询使用用户定义表类型
Create Type Table - Procedure - User Define Table Type 创建类型表-过程-用户定义表类型
@UserDefineTypeTable UserDefineTypeTable readonly @UserDefineTypeTable UserDefineTypeTable只读
insert into table1 col1, col2, col3 插入表1 col1,col2,col3
(select (选择
type.col1, type.col2, type,col3 type.col1,type.col2,type,col3
from @UserDefineTypeTable as type) 来自@UserDefineTypeTable作为类型)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.