Sql server 在sql server 2008中执行动态查询以从表@tblName=';获取的完整名称时出错;客户列表';
当我通过这个执行这个动态查询时,我试图获取客户的全名Sql server 在sql server 2008中执行动态查询以从表@tblName=';获取的完整名称时出错;客户列表';,sql-server,Sql Server,当我通过这个执行这个动态查询时,我试图获取客户的全名(名字+姓氏) 请让我知道我做错了什么 代码如下: Set @tblName ='Customer_List' Exec (N'Select First_Name'+' '+'Last_Name from'''+ @tblName+''' where Customer_Id in ('+ 'cast(1000 as nvarchar(10))' ); 我得到这个错误: (1 row(s
(名字+姓氏)
请让我知道我做错了什么
代码如下:
Set @tblName ='Customer_List'
Exec (N'Select First_Name'+' '+'Last_Name from'''+ @tblName+'''
where Customer_Id in ('+ 'cast(1000 as nvarchar(10))' );
我得到这个错误:
(1 row(s) affected)
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'dbo.Customer_List'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'dbo.Customer_List'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'dbo.Customer_List'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'dbo.Customer_List'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'dbo.Customer_List'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'dbo.Customer_List'.
试试这个
Set @tblName ='Customer_List' Exec (N'Select First_Name'+' '+'Last_Name from '+ @tblName+' where Customer_Id in ( cast(1000 as nvarchar(10) ))' );
试试这个1) 在中的
之后添加空格
2) 将)
括号添加到(10))
3) 删除表名周围的'
。
DECLARE @tblName AS VARCHAR(100)
Set @tblName ='TempTable'
Exec (N'Select First_Name'+' '+'Last_Name from '+ @tblName+'
where Customer_Id in ('+ 'cast(1000 as nvarchar(10)))' );
尝试以下查询:
DECLARE @sql as VARCHAR(1000)
SET @sql = 'Select First_Name + '' ''+ Last_Name from '+ @tblName + ' where Customer_Id in (' + CAST(1000 AS VARCHAR(1000)) + ')'
Exec (@sql)
调试动态sql时,您应该做的第一件事是打印sql字符串,以便查看要执行的操作。错误通常会变得非常明显。