且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

验证存储过程中的数据并在表中插入记录。

更新时间:2023-12-03 19:43:28

使用游标效率低下。只需这样做,并将所有无效列放在一行:



Using a cursor is inefficient. Just do it this way and get all invalid columns in one row:

INSERT INTO InvalidValidDataTable
(
    id,
    Col1IsValid,
    Col2IsValid,
    Col3IsValid,
    Col4IsValid,
    Col5IsValid
)
SELECT
       CASE WHEN col1 IS NULL OR LEN(col1) > 10 THEN 0 ELSE 1 END as Col1IsValid,
       CASE WHEN col2 IS NULL OR LEN(col2) > 50 THEN 0 ELSE 1 END as Col2IsValid,
       CASE WHEN col3 IS NULL OR col3 <= 0      THEN 0 ELSE 1 END as Col3IsValid,
       CASE WHEN col4 IS NULL OR LEN(col4) < 1 OR LEN(col4) > 10 THEN 0 ELSE 1 END as Col4IsValid,
       CASE WHEN col5 IS NULL OR LEN(col5) > 50 THEN 0 ELSE 1 END as Col5IsValid
FROM dbo.mytable





除此之外,正确实现的模式和前端将首先防止无效数据插入数据库,甚至不需要像这样的垃圾。此外,如果您担心数据库中存在无效数据,请在应用程序中处理该可能性并在SQL中进行适当的注释。更好的是,写一些将修复表内容的SQL,并对前端进行更改以防止将来发生这种情况。



最后,如果这是一个家庭作业,这是教导某人关于游标的一种不好的方式,因为这意味着模式设计可以是一个事后的想法,因为,游标!整个思维过程都被破坏了。



Beyond that, a properly implemented schema and front end will prevent invalid data from being inserted in the database in the first place, and crap like this wouldn't even be necessary. Furthermore, if you're concerned about the presence of invalid data being in the database, handle the possibility in the application and make appropriate comments in the SQL. Even better, write some SQL that will repair the table contents, and make changes to the front end to prevent this from happening in the future.

Lastly, if this is a homework assignment, it's a poor way to teach someone about cursors, because it implies that schema design can be an afterthought because, well, cursors! The whole thought process is damaged.