简体   繁体   English

SQL Server 2008 R2和SQL Server 2014中的TRUNCATE TABLE的名称解析

[英]Name Resolution of TRUNCATE TABLE in SQL Server 2008 R2 vs SQL Server 2014

We experienced an error in our code that was executed in SQL Server 2014 which we do not encounter in SQL Server 2008 R2. 我们在SQL Server 2014中执行的代码中遇到错误,而在SQL Server 2008 R2中未遇到此错误。

Our code is like this: 我们的代码是这样的:

IF EXISTS (
SELECT 1
FROM master.dbo.sysdatabases
WHERE name = N'WebDB'
)
BEGIN
    TRUNCATE TABLE [WebDB].[dbo].[webtable] 
END

The Truncate Table command will only execute if the WebDB exists. 截断表命令仅在WebDB存在的情况下执行。 In SQL Server 2008 R2, this code runs without any problems. 在SQL Server 2008 R2中,此代码可以正常运行。 In SQL Server 2014, there is a problem that when the WebDB doesn't exist, it will throw an error saying that 'Database 'WebDB' does not exist.'. 在SQL Server 2014中,存在一个问题,当WebDB不存在时,它将引发错误,指出“数据库'WebDB'不存在”。 It is doing name resolution of the TRUNCATE TABLE command prior to the actual execution. 在实际执行之前,它正在对TRUNCATE TABLE命令进行名称解析。

Can someone explain this change in behaviour for SQL Server 2014? 有人可以解释SQL Server 2014的行为变化吗?

The SQL Editor parses the code without any error but in runtime the SQL Engine throws error SQL编辑器解析代码没有任何错误,但是在运行时,SQL Engine会引发错误

I cannot explain the reason for change in behaviour but you can convert your sample code into dynamic SQL and execute with sp_executeSQL command as follows 我无法解释行为更改的原因,但是您可以将示例代码转换为动态SQL并使用sp_executeSQL命令执行,如下所示

IF EXISTS (
    SELECT * FROM master.dbo.sysdatabases WHERE name = N'WebDB'
)
BEGIN
    declare @sql nvarchar(100) = N'TRUNCATE TABLE [WebDB].[dbo].[webtable]'
    exec sp_executeSql @sql
END

Actually the problem is because the existence of the database is evaluated when parsing the script, before running it. 实际上,问题是因为在运行脚本之前在分析脚本时会评估数据库的存在。 All statements are parsed independently of the condition for their execution. 所有语句的解析均独立于其执行条件。

This is something which was not being done in SQL 2008. 这是SQL 2008中未完成的工作。

Anyway you can update your query as following. 无论如何,您可以按以下方式更新查询。

IF EXISTS (
SELECT 1
FROM master.dbo.sysdatabases
WHERE [name] = N'WebDB'
)
BEGIN
    DECLARE @T NVARCHAR(1000)
    SET @T = N'TRUNCATE TABLE [WebDB].[dbo].[webtable]'
    EXECUTE SP_EXECUTESQL @T 

END

This is not the SSMS behavior, this change has been done in the core, even if you run your query using SQLCMD you will observe the same behavior. 这不是SSMS行为,此更改已在核心中完成,即使您使用SQLCMD运行查询,也会观察到相同的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM