存储过程类型转换失败
存储过程如下:
create proc proc_SetAdminPermissions
@adminId int,
@actions varchar(4000)
as
begin
declare @userIfExists int,@sql varchar(500)
select @userIfExists=COUNT(*) from adminaction where adminid=@adminId
print @userIfExists
if(@userIfExists > 0)
begin
set @sql = 'update adminaction set actionids='+@actions +' where adminid=' +@adminId
end
else
begin
set @sql = 'insert into adminaction(adminid,actionids) values('+@adminId+','+@actions+')'
end
exec(@sql)
end
create proc proc_SetAdminPermissions
@adminId int,
@actions varchar(4000)
as
begin
declare @userIfExists int,@sql varchar(500)
select @userIfExists=COUNT(*) from adminaction where adminid=@adminId
print @userIfExists
if(@userIfExists > 0)
begin
set @sql = 'update adminaction set actionids='''+@actions +''' where adminid='+rtrim(@adminId)
end
else
begin
set @sql = 'insert into adminaction(adminid,actionids) values('''+@adminId+''','+rtrim(@actions)+')'
end
exec(@sql)
end
--actionids, adminid 字段如果不是整型,需要加引号
--拼字段串时,需要把INT转换为字符型,再相加
declare
@adminId int,
@actions varchar(4000)
SELECT @adminId = 1, @actions = 'test'
DECLARE @sql NVARCHAR(MAX)
set @sql = 'update adminaction set actionids='''+@actions +''' where adminid=' +CAST(@adminId AS VARCHAR(10))
PRINT @sql
set @sql = 'insert into adminaction(adminid,actionids) values('+CAST(@adminId AS VARCHAR(10))+','''+@actions+''')'
PRINT @sql
create proc proc_SetAdminPermissions
@adminId int,
@actions varchar(4000)
as
begin
declare @userIfExists int,@sql varchar(500)
select @userIfExists=COUNT(*) from adminaction where adminid=@adminId
print @userIfExists
if(@userIfExists > 0)
begin
set @sql = 'update adminaction set actionids='''+@actions +''' where adminid='+rtrim(@adminId)
end
else
begin
set @sql = 'insert into adminaction(adminid,actionids) values('''+CAST(@adminId AS VARCHAR)+''','+rtrim(@actions)+')'
end
exec(@sql)
end
--先看一下正常的语句
SELECT * FROM tablename WHERE fieldname LIKE '%test' ORDER BY FId
--如果想把上面的语句放到字符串中再用exec执行,步骤如下
--#1.把SQL中的'全部替换成''
SELECT * FROM tablename WHERE fieldname LIKE ''%test'' ORDER BY FId
--#2.放到变量中
DECLARE @sql NVARCHAR(max)
SET @sql = 'SELECT * FROM tablename WHERE fieldname LIKE ''%test'' ORDER BY FId'
--#3.替换参数(注意替换的参数必须都是字符类型),替换时直接: '+ @变量名 +',如果变量不是字符型,则转换成字符型(RTRIM(@变量名)或CAST或CONVERT)
DECLARE @变量名 NVARCHAR(10)
SET @变量名 = 'test'
SET @sql = 'SELECT * FROM tablename WHERE fieldname LIKE ''%'+ @变量名 +''' ORDER BY FId'
PRINT @sql
Create proc proc_SetAdminPermissions
@adminId int,
@actions varchar(4000)
as
begin
declare @userIfExists int,@sql varchar(500)
select @userIfExists=COUNT(*) from adminaction where adminid=@adminId
print @userIfExists
if(@userIfExists > 0)
begin
set @sql = 'update adminaction set actionids='''+@actions +''' where adminid='+cast(@adminId as varchar(50))
end
else
begin
set @sql = 'insert into adminaction(adminid,actionids) values('''+cast(@adminId as varchar(50))+''','+rtrim(@actions)+')'
end
exec(@sql)
end