我正在从 Excel 导入记录,我想避免重复。在 ASP Classic 中,我编写了一个检查数据库是否存在重复项的函数。如果找到一个,它会在用户名的末尾添加一个数字并再次检查用户名是否唯一,例如 petejones 变为 petejones1。不幸的是,这个脚本太慢了,因为数据库有大约 150k 条记录,而且搜索唯一性需要很长时间。有没有办法在 T-SQL 的 SQL Server 2008 中直接做同样的事情?所以整个过程会很快。有制作独特的过程吗?
这是经典 ASP 中的函数。我知道有更好的方法可以做到这一点,所以不要嘲笑我的脚本。
FUNCTION CreateUniqueUsername(str)
SET DbConn = Server.CreateObject("ADODB.connection")
DbConn.Open DSN_LINK
nCounter = 0
Unique = ""
IF InStr(str, "@") > 0 THEN
strUsername = Left(str,InStr(str, "@")-1)
ELSE
strUsername = str
END IF
strUsername = FormatUsername(strUsername)
strSQL = "SELECT UserName FROM Member WHERE UserName = '" & strUsername & "';"
SET rs = DbConn.Execute(strSQL)
IF rs.EOF AND rs.BOF THEN
nFinalUsername = strUsername
ELSE
DO UNTIL Unique = true
nCounter = nCounter + 1
nFinalUsername = strUsername & nCounter
strSQL2 = "SELECT UserName FROM Member WHERE UserName = '" & nFinalUsername & " ' "
SET objRS = DbConn.Execute(strSQL2)
IF objRS.EOF THEN
Unique = true
ELSE
intCount = intCount
END IF
LOOP
objRS.Close
SET objRS = Nothing
END IF
rs.Close
SET rs = Nothing
SET DbConn = Nothing
CreateUniqueUsername = nFinalUsername
END FUNCTION
FUNCTION FormatUsername(str)
Dim OutStr
IF ISNULL(str) THEN EXIT FUNCTION
OutStr = lCase(Trim(str))
OutStr = Replace(OutStr, "’", "")
OutStr = Replace(OutStr, "”", "")
OutStr = Replace(OutStr, "'","")
OutStr = Replace(OutStr, "&","and")
OutStr = Replace(OutStr, "'", "")
OutStr = Replace(OutStr, "*", "")
OutStr = Replace(OutStr, ".", "")
OutStr = Replace(OutStr, ",", "")
OutStr = Replace(OutStr, CHR(34),"")
OutStr = Replace(OutStr, " ","")
OutStr = Replace(OutStr, "|","")
OutStr = Replace(OutStr, "&","")
OutStr = Replace(OutStr, "[","")
OutStr = Replace(OutStr, ";", "")
OutStr = Replace(OutStr, "]","")
OutStr = Replace(OutStr, "(","")
OutStr = Replace(OutStr, ")","")
OutStr = Replace(OutStr, "{","")
OutStr = Replace(OutStr, "}","")
OutStr = Replace(OutStr, ":","")
OutStr = Replace(OutStr, "/","")
OutStr = Replace(OutStr, "\","")
OutStr = Replace(OutStr, "?","")
OutStr = Replace(OutStr, "@","")
OutStr = Replace(OutStr, "!","")
OutStr = Replace(OutStr, "_","")
OutStr = Replace(OutStr, "''","")
OutStr = Replace(OutStr, "%","")
OutStr = Replace(OutStr, "#","")
FormatUsername = OutStr
END FUNCTION
任何帮助将不胜感激,因为我仍在学习 SQL。