I’m using SQL Server 2008 R2 (T-SQL) and have dynamic SQL code, which inserting into temporary table some data.
If I run code in new query window or PRINT code and then run in new query window everything is allright, BUT if I try to run this from stored procedure it throw error
Msg 156, Level 15, State 1, Procedure users, Line 3
Incorrect syntax near the keyword 'FROM'.
If I remove line with INSERT INTO #viewsTmp (webId, listId, viewName, viewTitle), code runs fine.
I have similar code above within same stored procedure and that code is fine.
Temp table:
CREATE TABLE #viewsTmp
(
webId uniqueidentifier,
listId uniqueidentifier,
viewName NVARCHAR(128),
viewTitle NVARCHAR(255)
)
variable @databaseName is declared as parameter of stored procedure
@databaseName NVARCHAR(255)
Code which is OK in new query window, but not ok if is runned from stored procedure:
SET @sql = N'
INSERT INTO #viewsTmp (webId, listId, viewName, viewTitle)
SELECT c.tp_WebId, c.tp_ID, b.LeafName, c.tp_Title
FROM (
SELECT *
FROM (
SELECT [ListId], [LeafName], [Type], [WebId]
,ROW_NUMBER() OVER (PARTITION BY ListId ORDER BY DirName) AS RowNumber
FROM ['+@databaseName+'].[dbo].[Docs]
WHERE [LeafName] = ''users''
) AS a
WHERE [RowNumber] = 1 AND [Type] = 1
) AS b
INNER JOIN
(SELECT [tp_WebId], [tp_ID], [tp_Title] FROM ['+@databaseName+'].[dbo].[Lists])
AS c
ON b.ListId = c.tp_ID AND b.WebId = c.tp_WebId
';
--PRINT @sql
exec sp_executesql @sql;
What is wrong with this code?
I decomposed and composed code step by step with small modification as Dale Burrell advised….and code runs and don’t runs. I didn’t know what was that…and finally I discover one my mistake…
Code itself is ok, but I give @webId as parameter to call inner procedure which is called after code, and there was error. I had all rows with one webId, but exactly one row with another (exception in design) and I pass for this one row same webId as for another rows, and then in this subroutine error appeared. So error message was not for code above, but for some code in called procedure…
Oh my…5 hours of time….
In every way, thank you very much for trying help!
I learned another thing about errors in T-SQL today.