下面是为在商店中搜索商品而编写的存储过程。它在 SQL Server 2008 中运行良好。但是当我在 SQL Azure 中运行它时,我发现不支持 SELECT INTO。
我决定使用CREATE #Table
并使用INSERT INTO(Col) Values()
。
问题是基于搜索条件的列数是动态的。以下过程中的示例是DISTANCE
列。仅当用户选择城市时才会返回。
如何在以下过程中将 CREATE TABLE 和 INSERT INTO 与动态 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
有什么帮助/建议吗?