首页 > 解决方案 > SQL Server 迁移 2008 到 2016 - raiserror 语法错误

问题描述

我们将从 SQL Server 2008 迁移到 2016。我正在识别错误​​,我在触发器中收到以下错误:

'51001' 附近的语法不正确。

我查看Raiserror了 Microsoft 网站上的文档,但没有帮助。下面是SQL。任何帮助,将不胜感激。

IF (SELECT count(*) FROM dbo.u_sample_concrete ref, deleted
WHERE  ref.lab_cd =  deleted.lab_id) > 0
BEGIN
    RAISERROR 51001 ''Trigger td_tblLAB on table dbo.tblLAB:  Primary key values found in table dbo.u_sample_concrete (lab_cd).  Delete restricted; the transaction is being rolled back.''
    ROLLBACK TRANSACTION
    RETURN
END

标签: sql-servertsqlraiserror

解决方案


使用正确的语法添加到@DaleK 的答案中,问题RAISERRROR语法早已过时。IIRC,它在 20 年前被弃用(在 SQL Server 2000 版本中)并在 SQL Server 2012 中完全删除。

下面是一个 powershell 脚本,它使用T-SQL 脚本 DOM(也可通过Dacfx NuGet 包获得)来识别具有无效语法的现有 T-SQL 模块。不过,它不会捕获动态 SQL 中的问题。

$connectionString = "Data Source=.;Initial Catalog=YourDatabase;Integrated Security=SSPI"

try {

    $query = @"
SELECT 
      QUOTENAME(OBJECT_SCHEMA_NAME(object_id)) + N'.' + QUOTENAME(OBJECT_NAME(object_id)) AS ObjectName
    , OBJECTPROPERTY(object_id, 'ExecIsQuotedIdentOn') AS ExecIsQuotedIdentOn
    , definition 
FROM sys.sql_modules;
"@

    Add-Type -Path "C:\Program Files (x86)\Microsoft SQL Server\140\DAC\bin\Microsoft.SqlServer.TransactSql.ScriptDom.dll"

    $connection = New-Object Data.SqlClient.SqlConnection($connectionString)
    $command = New-Object Data.SqlClient.SqlCommand($query, $connection)
    $connection.Open()
    $reader = $command.ExecuteReader()
    while ($reader.Read()) {

        # use TSqlParser appropriate for your SQL Server version
        $parser = New-Object Microsoft.SqlServer.TransactSql.ScriptDom.TSql130Parser($reader["ExecIsQuotedIdentOn"])
        $parseErrors = New-Object Collections.Generic.List[Microsoft.SqlServer.TransactSql.ScriptDom.ParseError]
        $scriptReader = New-Object IO.StringReader($($reader["definition"]))

        Write-Host "Parsing $($reader["ObjectName"]) ..."
        [void]$parser.Parse($scriptReader, [ref]$parseErrors)
        if($parseErrors.Count -ne 0) {
            Write-Host "Parsing errors for object $($reader["ObjectName"]): $($parseErrors | ConvertTo-Json)" -ForegroundColor Yellow
        }

    }
    $connecton.Close()
}    
catch {
    throw
}

推荐阅读