SQL Exec can't execute long strings - sql

This is my code
DECLARE #sql nvarchar(4000)
set #sql = 'WITH CTE AS
(
Select *, ROW_NUMBER() OVER (ORDER BY ' + #order + ' ' + #Desc + ') AS RowNum
from (SELECT ID, Subject from a
WHERE (Subject LIKE N''%'' + #searchText + N''%''))
)
SELECT *
FROM CTE
WHERE RowNum BETWEEN (#pageIndex - 1) * #pageSize + 1
AND #pageIndex * #pageSize ;';
where #order = "ID" and #pageIndex = 1 and #pageSize = 5 and #searchText = 'a' and #Desc = 'DESC'
I wrote
select #sql
to see if #sql is executable. I copied it and pasted it and ran it. it worked.
then I wrote
exec #sql
error! it seems exec just tried to execute some characters from the first of #sql. Is there any limitations on #sql?
p.s: The error is like this
The name '.........someth' is not a valid identifier.

Please try the below code.
DECLARE #sql nvarchar(max)
set #sql = '.............something executable.................';
This error may occurred due to length of the string exceed more than 4000 characters

Related

Column Matching Data featch in SQL

DECLARE #ompid NVARCHAR(max)
DECLARE #Names VARCHAR(max)
SELECT #Names = COALESCE(#Names + ') as ' + Variable_Name + ' ,AVG(', 'AVG(') + Variable_Name
FROM charttest
WHERE ompid = 125
DECLARE #lastcol NVARCHAR(100) = (
SELECT TOP 1 (Variable_Name)
FROM charttest
WHERE ompid = 125
ORDER BY Variable_Name ASC
)
DECLARE #Names2 NVARCHAR(500) = #Names + ') as ' + #lastcol + ''
DECLARE #sql NVARCHAR(500)
SET #sql = 'SELECT ' + #Names2 + ' FROM ompvaribles'
EXEC (#sql)
This is my sql query i had show second table avg but not getting second table records.
I'm not sure what is actually not working with your query (I'm assuming you get an error), but in order to execute the dynamic query you've build you need to use:
exec sp_executesql #sql

How to execute string as query inside a CTE in SQL Server

I am using CTE like below... But I am getting an error like
No column name was specified for column 1 of 'TempResult'.
Also here I am passing #Query from another stored procedure, and in this procedure I need to execute that #Query inside CTE TempResult.
CREATE PROCEDURE [dbo].[SelectAllProjectPaging]
#CurrentPage int,
#RecordsPerPage int,
#Column varchar(50),
#Query nvarchar(max)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #query nvarchar(max)
SET #query = 'ROW_NUMBER() OVER(ORDER BY ProjectList.ProjectId DESC) as RowNumber,' + #Query
-- Insert statements for procedure here
DECLARE #FirstRecord int, #LastRecord int
SELECT #FirstRecord = (#CurrentPage - 1) * #RecordsPerPage
SELECT #LastRecord = (#CurrentPage * #RecordsPerPage + 1);
WITH TempResult as
(
Select #query
)
SELECT TOP (#LastRecord - 1) *
FROM TempResult
WHERE RowNumber > #FirstRecord
AND RowNumber < #LastRecord;
SELECT COUNT(*) as count
FROM ProjectList
End
You need to make the entire query with dynamic sql. something like this:
SET #query= 'WITH TempResult as
(
SELECT + ' + #query +
')
SELECT TOP (' + CAST((#LastRecord - 1) AS VARCHAR(20)) +
') * FROM TempResult
WHERE RowNumber > ' + CAST(#FirstRecord AS VARCHAR(20)) +
' AND RowNumber < ' + CAST(#LastRecord AS VARCHAR(20)) + '; '
EXECUTE #query
Edit
To the comment. Yes it should select what I can see. The #query is equals to:
set #query = 'ROW_NUMBER() OVER(ORDER BY ProjectList.ProjectId DESC) as RowNumber,'+ #query
Then you will need:
SELECT ' ROW_NUMBER() OVER(ORDER BY ProjectList.ProjectId DESC) as RowNumber,' + #query
Your "With TempResult As" has to be extended a bit, containing the column names to be used.
Example
With TempResult (column1, column2, column3) as
(
select #query
)
Ref:
WITH expression_name [ ( column_name [,...n] ) ]
AS
( CTE_query_definition )
From http://technet.microsoft.com/en-us/library/ms190766%28v=sql.105%29.aspx

Incorrect syntax - T-Sql

The idea is to have a generic stored procedure to get data from all tables. This query gives an error
Incorrect Syntax new #OrderByClause.
Where am I going wrong?
declare #TableName nvarchar(50), #ColName nvarchar(50),
#OrderByClause nvarchar(50), #Code nvarchar(max),
#StartIndex nvarchar(50), #EndIndex nvarchar(50)
set #TableName = 'tblCountry'
set #ColName = 'countryname'
set #OrderByClause = 'desc'
set #StartIndex = '2'
set #EndIndex = '10'
select #Code = 'With temp as (select row_number()
over (order by #ColName #OrderByClause) as row, * from #TableName)
select * from temp where row between #StartIndex and #EndIndex'
set #param = '#TableName nvarchar(50), #ColName nvarchar(50),
#OrderByClause nvarchar(50), #StartIndex nvarchar(50),
#EndIndex nvarchar(50)'
execute sp_executesql #Code, #param #colname, #OrderByClause, #TableName,
#StartIndex, #EndIndex
EDIT:
This is working though....
select #code = 'with temp as (select row_number() over (order by '+
#colname+' '+#OrderByClause+') as row, * from '+#tablename+')
select * from temp where row between '+#startIndex+' and '+#EndIndex
execute sp_executesql #code
You missed a comma on the last statement:
execute sp_executesql #Code, #param #colname, #OrderByClause, #TableName,
should be
execute sp_executesql #Code, #param, #colname, #OrderByClause, #TableName,
The second thing is that #RahulTripathi was correct (but for a different reason), this is invalid:
select #Code = 'With temp as (select row_number()
over (order by #ColName #OrderByClause) as row, * from #TableName)
select * from temp where row between #StartIndex and #EndIndex'
The #OrderByClause cannot be there because ASC and DESC are syntactical elements of the ORDER BY clause and cannot be variables.
Next, you have not defined #TableName correctly in the dynamic SQL. You are using it as a Table variable in the commands above, but you are passing (and defining) it as an NVarchar(50).
I think your variables are not defined neither interpreted (in the case of desc) in the sp_executesql scope.
Try to "expand" before calling sp_executesql with + and quotes when you assign #code:
select #Code = 'With temp as (select row_number()
over (order by '+ #ColName +' '+ #OrderByClause +' ) as row, * from '+ #TableName +')
select * from temp where row between '+ #StartIndex + ' and '+#EndIndex
(did only one row)
or you could pass parameters to sp_executesql but you will have to choose different names
and not for #ColName, #tableName and #OrderByClause I guess (you can't put variables instead of sql text anywhere in a query)
select #Code = 'With temp as (select row_number()
over (order by '+#ColName+' '+#OrderByClause+') as row, * from '+#TableName+')
select * from temp where row between #pStartIndex and #pEndIndex'
execute sp_executesql #code, #pStartIndex=#StartIndex, #pEndIndex=#EndIndex

Select from table with dynamic compute name

I want to write query in which name table will dynamicaly compute. I have code like this below. What should I put in 'magic code' region?
DECLARE #myTableName nvarchar(100) = 'sch'
+ CAST(#nowYear as VARCHAR(5))
+ 'Q'
+ CAST(#nowQuarter as VARCHAR(3))
+ '.[tVisits]'
-- magic code --
myTable = DoSomething(#aktTableName)
-- magic code --
SELECT * FROM myTable
I use MS SQL Server 2012
You need use the dynamic SQL -
DECLARE
#nowYear INT = 2013
, #nowQuarter INT = 1
DECLARE #myTableName NVARCHAR(100) = '[sch'
+ CAST(#nowYear AS VARCHAR(5))
+ 'Q'
+ CAST(#nowQuarter AS VARCHAR(3))
+ '].[tVisits]'
DECLARE #SQL NVARCHAR(MAX) = N'SELECT * FROM ' + #myTableName
EXEC sys.sp_executesql #SQL
Instead of SELECT * FROM myTable
You need to do something like
DECLARE #sql nvarchar(4000)
SELECT #sql = ' SELECT * FROM ' + #myTable -- #myTable is a string containing qualified table name
EXEC sp_executesql #sql
Note that sp_executesql allows for a parameterized query - check its documentation

DynamicSQL using sp_executesql Error

I keep getting an error with the following stored procedure. I had it working correctly using EXEC, then I switched to sp_executesql and I haven't been able to get it to execute. I keep getting the following error: Incorrect syntax near '#numberOfItems'.
ALTER PROCEDURE dbo.FetchResourcesToProcess
(
#tableName nvarchar(MAX),
#numberOfItems int
)
AS
BEGIN
DECLARE #SQL nvarchar(MAX);
SET NOCOUNT ON;
SET #SQL = N'Select TOP #numberOfItems * from ' + #tableName + N' where Active = 1 AND BeingProcessed = 0'
EXEC sp_executesql #SQL, N'#numberOfItems int', #numberOfItems
END
Tablename is a string structured as follows: "[TABLENAME]".
Thanks
You probably need to place number of items into the string the same way you are the table name
SET #SQL = N'Select TOP ' + Convert(varchar(10),#numberOfItems) + ' * from ' + #tableName + N' where Active = 1 AND BeingProcessed = 0'
I think you can only use parameters for sp_executesql statement in positions where variables are allowed.
use master;
declare #numberOfItems int;
set #numberOfItems = 2;
Select TOP #numberOfItems * from dbo.spt_values
Incorrect syntax near '#numberOfItems'.
use master;
declare #table varchar(max);
set #table = 'dbo.spt_values';
Select * from #table
Must declare the table variable "#table".
use master;
declare #numberOfItems int;
set #numberOfItems = 2;
Select TOP(#numberOfItems) * from dbo.spt_values
(2 row(s) affected)
Solution 1 (parenthesis, recommended):
SET #SQL = N'Select TOP(#numberOfItems) * from ' + #tableName + N' where Active = 1 AND BeingProcessed = 0'
Solution 2 (concatenation, make sure to prevent SQL injection!):
SET #SQL = N'Select TOP '+cast(#numberOfItems as nvarchar(MAX))+' * from ' + #tableName + N' where Active = 1 AND BeingProcessed = 0'
EXEC sp_executesql #SQL