我希望在执行之前获取@sql的计数。但我不能将表名与我的参数值连接起来。
SQL:
SET @count = (SELECT count(*) as tblcount
FROM RDL_tbl_UserManagement_UserInfo_ + @table_prefix_name
WHERE partnerID = CAST(@partnerID AS VARCHAR)
AND userID = CAST(@adminUserID AS VARCHAR)
AND addressType = 'H')
IF @count = 0
BEGIN
SET @sql = 'SELECT * FROM RDL_tbl_UserManagement_UserInfo_' + @table_prefix_name +
' WHERE partnerID = ' + CAST(@partnerID AS VARCHAR) +
' AND userID = ' + CAST(@adminUserID AS VARCHAR) +
' AND addressType= ''MZ'' ORDER BY company'
END
ELSE
BEGIN
SET @sql = 'SELECT * FROM RDL_tbl_UserManagement_UserInfo_' + @table_prefix_name +
' WHERE partnerID = ' + CAST(@partnerID AS VARCHAR) +
' AND userID = ' + CAST(@adminUserID AS VARCHAR) +
' AND addressType=''H'' ORDER BY company'
END
Exec (@sql)
怎么做?
答案 0 :(得分:1)
declare @count int
SET @sql = 'SELECT @count =count(*)
FROM RDL_tbl_UserManagement_UserInfo_'+@table_prefix_name +'
WHERE partnerID = CAST(@partnerID AS VARCHAR)
AND userID = CAST(@adminUserID AS VARCHAR)
AND addressType = ''H'')'
EXEC sp_executesql @sql, N'@count int OUTPUT',
@count OUTPUT
IF @count = 0
BEGIN
SET @sql = 'SELECT * FROM RDL_tbl_UserManagement_UserInfo_' + @table_prefix_name +
' WHERE partnerID = ' + CAST(@partnerID AS VARCHAR) +
' AND userID = ' + CAST(@adminUserID AS VARCHAR) +
' AND addressType= ''MZ'' ORDER BY company'
END
ELSE
BEGIN
SET @sql = 'SELECT * FROM RDL_tbl_UserManagement_UserInfo_' + @table_prefix_name +
' WHERE partnerID = ' + CAST(@partnerID AS VARCHAR) +
' AND userID = ' + CAST(@adminUserID AS VARCHAR) +
' AND addressType=''H'' ORDER BY company'
END
Exec (@sql)
答案 1 :(得分:0)
只需将@sql参数中的所有内容都作为
declare @sql navarchar(max)
set @sql =
'declare @count int
SET @count = (SELECT count(*) as tblcount FROM RDL_tbl_UserManagement_UserInfo_'+@table_prefix_name+' WHERE partnerID='+cast(@partnerID as varchar)+' AND userID='+cast(@adminUserID as varchar)+' AND addressType=''H'')
IF @count = 0
BEGIN
SELECT * FROM RDL_tbl_UserManagement_UserInfo_'+@table_prefix_name+' WHERE partnerID='+cast(@partnerID as varchar)+' and userID='+cast(@adminUserID as varchar)+' AND addressType=''MZ'' ORDER BY company
END
ELSE
BEGIN
SELECT * FROM RDL_tbl_UserManagement_UserInfo_'+@table_prefix_name+' WHERE partnerID='+cast(@partnerID as varchar)+' and userID='+cast(@adminUserID as varchar)+' AND addressType=''H'' ORDER BY company
END
'
Exec sp_executesql @sql