以下是为搜索商店中的商品而编写的存储过程。它在SQL Server 2008中运行良好。但是当我在SQL Azure中运行它时,我发现不支持SELECT INTO。
我决定使用CREATE #Table
并使用INSERT INTO(Col) Values()
。
问题是根据搜索条件,列数是动态的。以下过程中的示例为DISTANCE
列。仅当用户选择城市时才会返回此内容。
如何在以下过程中使用CREATE TABLE和INSERT INTO与Dynamic SQL?
CREATE PROCEDURE [dbo].[SearchItems]
(
@ShopId INT
,@unitItems INT = 20
,@sortOrder INT = 0
,@language CHAR(2) = 'EN'
,@catId INT
,@search NVARCHAR(100) = ''
,@cityId INT = 0
,@page INT
,@currentDate DATETIME2(0)
,@currentUserId INT = 0
,@itemType TINYINT = 0
,@unitRows INT OUTPUT
,@unitPages INT OUTPUT
)
AS
BEGIN
SET XACT_ABORT ON
SET NOCOUNT ON
DECLARE @sql NVARCHAR(MAX)
,@sqlSelect NVARCHAR(MAX) = ''
,@sqlTempTable NVARCHAR(MAX) = 'itemSearch'
,@sqlInto NVARCHAR(MAX) = ''
,@sqlFrom NVARCHAR(MAX) = ''
,@sqlClause NVARCHAR(MAX) = ''
,@sqlGroup NVARCHAR(MAX) = ''
,@params NVARCHAR(MAX)
,@sortOrderString NVARCHAR(MAX) = 'ORDER BY IT.CREATEDATE DESC'
SET @sqlSelect =
'SELECT
IT.ITEMId
,IT.USERId
,IT.ShopId
,IT.ITEMID
,IT.ITEMNAME
,IT.LASTUPDATED
,CY.COUNTRYNAME AS COUNTRYNAME
,CI.CITYNAME AS CITY
,ROW_NUMBER() OVER (' + @sortOrderString + ') AS RowNumber'
SET @sqlGroup =
' GROUP BY IT.ITEMId
,IT.USERId
,IT.ShopId
,IT.ITEMID
,IT.ITEMNAME
,IT.LASTUPDATED
,CY.COUNTRYNAME
,CI.CITYNAME'
SET @sqlFrom =
' FROM dbo.ITEM AS IT
INNER JOIN dbo.Shop AS J
ON IT.ShopId = J.ShopId
INNER JOIN dbo.CITY AS CI
ON CI.CITYID = J.CITYID
INNER JOIN dbo.COUNTRY AS CY
ON CI.COUNTRYISO = CY.COUNTRYISO
INNER JOIN dbo.REGION AS R
ON CI.REGIONId = R.REGIONId'
IF (@cityId > 0)
BEGIN
SET @sqlFrom = @sqlFrom +
' INNER JOIN dbo.CITY AS CI2
ON CI2.CITYID = @cityId'
SET @sqlSelect = @sqlSelect +
',dbo.GetDistance(CI2.LATITUDE) AS DISTANCE '
SET @sqlGroup = @sqlGroup +
',CI2.LATITUDE'
END
SET @sqlInto = ' INTO ' + @sqlTempTable + ' ';
SET @sql = @sqlSelect +
@sqlInto +
@sqlFrom +
@sqlClause +
@sqlGroup
END
任何帮助/建议?
答案 0 :(得分:1)
你的临时表也需要动态创建,否则,它不在同一个上下文中,它会返回你的临时表未定义的错误。基本上你做了以下事情: 添加如下参数
declare @definetmp varchar(max)
set @definetemp =' declare @tempTable table ( ItemID int,
UserID int,
....
'
.....
set @sqlInto = 'Insert into @tempTable'
......
set @sql = @definetemp +
@sqlInto +
@sqlSelect+
....
关键是,您的临时表也是在动态sql中创建的。