I'm trying to execute an inline SQL statement within a stored procedure. I'm working with SQL Server 2008.
The problem is that I can't execute the first inline statement (with WHERE
clause). It crashes because the string within EXEC(...)
is dynamically created and all concatenated variables must be of type varchar
.
Error that appears when calling procedure:
An expression of non-boolean type specified in a context where a condition is expected, near 'ORDER'.
The procedure looks like:
CREATE PROCEDURE loadMyRows
@table_name nvarchar(50),
@bounding_box varchar(8000)
AS
BEGIN
-- *********************************** COMMENT *********************************
-- ** This two code lines are correct and will return true (1) or false (0), **
-- ** but they doesn't work within inline EXEC(...) **
--DECLARE @bb geometry = geometry::STGeomFromText(@bounding_box, 4326);
--select TOP(5) wkt.STWithin(@bb) AS 'bool'
-- *********************************** COMMENT *********************************
IF @bounding_box <> ''
BEGIN
DECLARE @bb geometry = geometry::STGeomFromText(@bounding_box, 4326);
EXEC(
'SELECT TOP (' + @row_limit + ') * ' +
'FROM ' + @real_table_name + ' ' +
'WHERE wkt.STWithin('+@bb+') ' + -- <-- doesn't work :-(
-- 'WHERE wkt.STWithin(geometry::STGeomFromText('''+@bounding_box+''', 4326)) ' +
-- ^^ doesn't work, too :-(
'ORDER BY id ASC '
);
END
ELSE
BEGIN
EXEC(
'SELECT TOP (' + @row_limit + ') * ' +
'FROM ' + @real_table_name + ' ' +
'ORDER BY id ASC'
);
END
END