请教将字符串转换为 uniqueidentifier 时出现语法错误如何解决
查询管理器运行
DECLARE @jobid uniqueidentifier
EXEC msdb.dbo.sp_add_job
@job_name = N'作业名称',@job_id = @jobid OUTPUT,@delete_level = 3
DECLARE @sql nvarchar(400),@dbname sysname
SELECT @dbname=DB_NAME(),
@sql=N'select s='kill '+cast(spid as varchar) from master..sysprocesses where dbid=db_id(@dbname) '
出现将字符串转换为 uniqueidentifier 时出现语法错误,经查为dbid=db_id(@dbname)写法错误,请教应如何写@sql=N'select s='kill '+cast(spid as varchar) from master..sysprocesses where dbid=db_id(@dbname) '
[解决办法]
DECLARE @sql nvarchar(400),@dbname sysname
SELECT
@dbname=DB_NAME(),
@sql=N'select s=''kill ''+cast(spid as varchar) from master..sysprocesses where dbid= ' + CAST(db_id(@dbname) AS VARCHAR(10))
SELECT @dbname, @sql
/*select s='kill '+cast(spid as varchar) from master..sysprocesses where dbid= 6*/
--注意
--#1.字符串中的'需要转义,即''代表一个'
--#2.字符类型与整数类型运算时,默认转换成整数类型后再运算
--#3.用cast转换时,varchar不写长度时,默认30.即可varchar(30).建议根据需要指明长度