I have a drop down list on my web page, the selected item of which has to be passed to the Stored Procedure query in the database. However, I am getting a strange error here at adp.Fill(ds) in my bind method.
The exception always says "Incorrect syntax near the keyword 'to'.", where to is always the second word in the drop down option.
For eg: Items in dropdown- 9 to 5 (2nd word: to) , age of empires (2nd word: of)
Exceptions:
Incorrect syntax near the keyword 'to'
Incorrect syntax near the keyword 'of' etc.
Here's the method that I am using:
private void Bind(string ss)
{
SqlDataAdapter adp = new SqlDataAdapter("Retrieve", ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
DataSet ds = new DataSet();
adp.SelectCommand.CommandType = CommandType.StoredProcedure;
adp.SelectCommand.Parameters.Add("#s1", SqlDbType.NVarChar, 255).Value = ss;
adp.SelectCommand.Parameters.Add("#s2", SqlDbType.NVarChar, 255).Value = DropDownList1.SelectedItem.ToString();
adp.Fill(ds);
DataList1.DataSource = ds;
DataList1.DataBind();
}
StoredProcedure
ALTER PROCEDURE [dbo].[Retrieve_SegmentedQ]
(
#s1 nvarchar(255),
#s2 nvarchar(255)
)
AS
BEGIN
DECLARE #query nvarchar(max)
SET #query = 'SELECT DISTINCT Details from tbData WHERE Name IN (' + #s1 + ') AND UnsegmentedQuery=' + #s2
exec sp_executesql #query
END
Any suggestions what's wrong here?
update the procedure like below
ALTER PROCEDURE [dbo].[Retrieve_SegmentedQ]
(
#s1 nvarchar(255),
#s2 nvarchar(255)
)
AS
BEGIN
DECLARE #query nvarchar(max)
SET #query = 'SELECT DISTINCT Details from tbData WHERE Name IN (''' + #s1 + ''') AND UnsegmentedQuery=''' + #s2 + ''''
exec sp_executesql #query
END
The bug is here:
SET #query = 'SELECT DISTINCT Details from tbData WHERE Name IN (' + #s1 + ') AND UnsegmentedQuery=' + #s2
You have stored procedure but using it as query, so making something like sql injection. as result you will have following query:
SET #query = 'SELECT DISTINCT Details from tbData WHERE Name IN (5 to 9) AND UnsegmentedQuery=age of empires
which is wrong.
make it in following way add single quotation marks to your params.
SET #query = 'SELECT DISTINCT Details from tbData WHERE Name IN (''' + #s1 + ''') AND UnsegmentedQuery=''' + #s2 + ''''
Your command text name should be same as your procedure name....and here they both are different
Related
I am developing an application for my project using C# windows form. I have a dynamic SQL script, please refer the below script:
I need to give this Dynamic SQL script in C# : (command part)
`command.CommandType = CommandType.Text;
command.CommandText =???`
Please help me out in this. If I give normally I am getting Exception error in #SQL part.
`
Declare #Sql nvarchar(max)
Set #Sql ='CREATE FUNCTION [dbo].geoid (#InStr VARCHAR(MAX))
RETURNS #TempTable TABLE
(id int not null)
AS
BEGIN
SET #InStr = #InStr + '',''
DECLARE #SP INT
DECLARE #VALUE VARCHAR(1000)
WHILE PATINDEX(''%,%'', #INSTR ) <> 0---(1,2,3,4,5,)
BEGIN
SELECT #SP = PATINDEX(''%,%'',#INSTR)
SELECT #VALUE = LEFT(#INSTR , #SP - 1)--=1
SELECT #INSTR = STUFF(#INSTR, 1, #SP, '''')--(2,3,4,5)
INSERT INTO #TempTable(id) VALUES (#VALUE)
END
RETURN
END
'
declare #xyz varchar(200)
Exec (#sql)
`
Why are you creating the function using command text
You can do something like below for dynamic query
public void Test()
{
string commandText = "Select CatId From tbl_T2H_Category Where Category IN (#cat_1,#cat_2 #cat_3)";
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("#cat1", SqlDbType.Varchar);
command.Parameters["#cat1"].Value = "category1";
command.Parameters.Add("#cat2", SqlDbType.Varchar);
command.Parameters["#cat2"].Value = "category2";
command.Parameters.Add("#cat3", SqlDbType.Varchar);
command.Parameters["#cat3"].Value = "category3";
}
I am trying to execute this query:
declare #tablename varchar(50)
set #tablename = 'test'
select * from #tablename
This produces the following error:
Msg 1087, Level 16, State 1, Line 5
Must declare the table variable "#tablename".
What's the right way to have the table name populated dynamically?
For static queries, like the one in your question, table names and column names need to be static.
For dynamic queries, you should generate the full SQL dynamically, and use sp_executesql to execute it.
Here is an example of a script used to compare data between the same tables of different databases:
Static query:
SELECT * FROM [DB_ONE].[dbo].[ACTY]
EXCEPT
SELECT * FROM [DB_TWO].[dbo].[ACTY]
Since I want to easily change the name of table and schema, I have created this dynamic query:
declare #schema sysname;
declare #table sysname;
declare #query nvarchar(max);
set #schema = 'dbo'
set #table = 'ACTY'
set #query = '
SELECT * FROM [DB_ONE].' + QUOTENAME(#schema) + '.' + QUOTENAME(#table) + '
EXCEPT
SELECT * FROM [DB_TWO].' + QUOTENAME(#schema) + '.' + QUOTENAME(#table);
EXEC sp_executesql #query
Since dynamic queries have many details that need to be considered and they are hard to maintain, I recommend that you read: The curse and blessings of dynamic SQL
Change your last statement to this:
EXEC('SELECT * FROM ' + #tablename)
This is how I do mine in a stored procedure. The first block will declare the variable, and set the table name based on the current year and month name, in this case TEST_2012OCTOBER. I then check if it exists in the database already, and remove if it does. Then the next block will use a SELECT INTO statement to create the table and populate it with records from another table with parameters.
--DECLARE TABLE NAME VARIABLE DYNAMICALLY
DECLARE #table_name varchar(max)
SET #table_name =
(SELECT 'TEST_'
+ DATENAME(YEAR,GETDATE())
+ UPPER(DATENAME(MONTH,GETDATE())) )
--DROP THE TABLE IF IT ALREADY EXISTS
IF EXISTS(SELECT name
FROM sysobjects
WHERE name = #table_name AND xtype = 'U')
BEGIN
EXEC('drop table ' + #table_name)
END
--CREATES TABLE FROM DYNAMIC VARIABLE AND INSERTS ROWS FROM ANOTHER TABLE
EXEC('SELECT * INTO ' + #table_name + ' FROM dbo.MASTER WHERE STATUS_CD = ''A''')
Use:
CREATE PROCEDURE [dbo].[GetByName]
#TableName NVARCHAR(100)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #sSQL nvarchar(500);
SELECT #sSQL = N'SELECT * FROM' + QUOTENAME(#TableName);
EXEC sp_executesql #sSQL
END
You can't use a table name for a variable. You'd have to do this instead:
DECLARE #sqlCommand varchar(1000)
SET #sqlCommand = 'SELECT * from yourtable'
EXEC (#sqlCommand)
You'll need to generate the SQL content dynamically:
declare #tablename varchar(50)
set #tablename = 'test'
declare #sql varchar(500)
set #sql = 'select * from ' + #tablename
exec (#sql)
Use sp_executesql to execute any SQL, e.g.
DECLARE #tbl sysname,
#sql nvarchar(4000),
#params nvarchar(4000),
#count int
DECLARE tblcur CURSOR STATIC LOCAL FOR
SELECT object_name(id) FROM syscolumns WHERE name = 'LastUpdated'
ORDER BY 1
OPEN tblcur
WHILE 1 = 1
BEGIN
FETCH tblcur INTO #tbl
IF ##fetch_status <> 0
BREAK
SELECT #sql =
N' SELECT #cnt = COUNT(*) FROM dbo.' + quotename(#tbl) +
N' WHERE LastUpdated BETWEEN #fromdate AND ' +
N' coalesce(#todate, ''99991231'')'
SELECT #params = N'#fromdate datetime, ' +
N'#todate datetime = NULL, ' +
N'#cnt int OUTPUT'
EXEC sp_executesql #sql, #params, '20060101', #cnt = #count OUTPUT
PRINT #tbl + ': ' + convert(varchar(10), #count) + ' modified rows.'
END
DEALLOCATE tblcur
You need to use the SQL Server dynamic SQL:
DECLARE #table NVARCHAR(128),
#sql NVARCHAR(MAX);
SET #table = N'tableName';
SET #sql = N'SELECT * FROM ' + #table;
Use EXEC to execute any SQL:
EXEC (#sql)
Use EXEC sp_executesql to execute any SQL:
EXEC sp_executesql #sql;
Use EXECUTE sp_executesql to execute any SQL:
EXECUTE sp_executesql #sql
Declare #tablename varchar(50)
set #tablename = 'Your table Name'
EXEC('select * from ' + #tablename)
Also, you can use this...
DECLARE #SeqID varchar(150);
DECLARE #TableName varchar(150);
SET #TableName = (Select TableName from Table);
SET #SeqID = 'SELECT NEXT VALUE FOR ' + #TableName + '_Data'
exec (#SeqID)
Declare #fs_e int, #C_Tables CURSOR, #Table varchar(50)
SET #C_Tables = CURSOR FOR
select name from sysobjects where OBJECTPROPERTY(id, N'IsUserTable') = 1 AND name like 'TR_%'
OPEN #C_Tables
FETCH #C_Tables INTO #Table
SELECT #fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '#C_Tables'
WHILE ( #fs_e <> -1)
BEGIN
exec('Select * from ' + #Table)
FETCH #C_Tables INTO #Table
SELECT #fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '#C_Tables'
END
I have one question on the TSQL Linked Server Query. Linked Server is GIS enforced so we pass the coordinates to that server which it returns the data from the Linked Server. Please find the below-working query.
DECLARE #input varchar(max), #sql varchar(max);
SET #input = N'((-119.470830216356 46.2642458295079,-119.470722927989 46.2642050348762,-119.470076515615 46.2647075484513,-119.470240130371 46.2647075484512,-119.470830216356 46.2642458295079))'
BEGIN
SELECT #sql = 'select * from openquery([LinkedServerName],''DECLARE #b geometry;
SET #b = geometry::STGeomFromText(''''POLYGON '+ #input + ' '''', 4326);
SET #b = #b.MakeValid();
SELECT * from [Database].[Table] AS b
where b.Shape.STIntersects(#b.STCentroid()) = 1'')'
END
EXEC(#sql)
But the issue is sometimes we have to pass more than 8000 characters to the input parameter #input since it is varchar(max) and EXEC command both have an 8000 character limitation. So we are trying to get rid of Dynamic SQL so that we can pass the input using 2 input variables (We have implemented splitting the input into subsets each of 8000 characters in our C# code and sending them as 2 different inputs to the SQL Query). We have tried the below query in the Actual Server (Linked Server) which is working fine.
DECLARE #b geometry
SET #input = N'((-119.470830216356 46.2642458295079,-119.470722927989 46.2642050348762,'
SET #input2 = N'-119.470076515615 46.2647075484513,-119.470240130371 46.2647075484512,-119.470830216356 46.2642458295079))'
SELECT #b = geometry::STGeomFromText('POLYGON ' + #input + #input2 + '', 4326)
SELECT #b = #b.MakeValid()
SELECT * FROM [Database].[TableName] AS b
WHERE b.Shape.STIntersects(#b.STCentroid()) = 1
We tried below SQL Linked query in our local server but it is throwing below error
DECLARE #input varchar(max), #input2 varchar(max);
SET #input = N'((-119.470830216356 46.2642458295079,-119.470722927989 46.2642050348762,'
SET #input2 = N'-119.470076515615 46.2647075484513,-119.470240130371 46.2647075484512,-119.470830216356 46.2642458295079))'
SELECT * FROM OPENQUERY([LinkedServerName],
'DECLARE #b geometry;
SELECT #b = geometry::STGeomFromText(''''POLYGON ' + #input + #input2 + '' ', 4326);
SELECT #b = #b.MakeValid();
SELECT * FROM [DatabaseName].[TableName] AS b
where b.Shape.STIntersects(#b.STCentroid()) = 1') AS AD
In the above query, an issue has been highlighted in the attached image.
Help is really appreciated.
Not worried about SQL Injection or anything of the like, just trying to get this to work. Using SSMS and Visual Studio.
I have C# code that passes a variable, GlobalVariables.username, to an SQL parameter.
private void btnNext_Click(object sender, EventArgs e)
{
if (checkIntrotoPublicSpeaking.Checked || checkEffectiveOralCommunication.Checked || checkProfComm.Checked)
{
List<SqlParameter> sqlOralComm = new List<SqlParameter>();
sqlOralComm.Add(new SqlParameter("Username", GlobalVariables.username));
sqlOralComm.Add(new SqlParameter("IntrotoPublicSpeaking", cboxIntrotoPublicSpeaking.Text));
sqlOralComm.Add(new SqlParameter("EffectiveOralCommunication", cboxEffectiveOralCommunication.Text));
sqlOralComm.Add(new SqlParameter("ProfComm", cboxProfComm.Text));
DAL.ExecSP("CreateOralComm", sqlOralComm);
}
}
I've been reading into Dynamic SQL and saw that to pass the table name as a parameter, you have to construct it manually and execute it as "SET..." etc, etc. I've been trying slightly different modifications of the last 3 lines below. Each time, I'm greeted with an "invalid syntax near ..." exception pertaining to different parts of that line. In stack exchange it's broken into 3 lines but in SSMS it's one line, a little easier to read.
Status is nvarchar column and Course is an int column.
ALTER PROCEDURE [dbo].[CreateOralComm]
-- Add the parameters for the stored procedure here
#Username nvarchar(30),
#IntrotoPublicSpeaking nvarchar(3),
#EffectiveOralCommunication nvarchar(3),
#ProfComm nvarchar(3)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
DECLARE #sql as nvarchar(max)
SET #sql = 'UPDATE ' + #Username + ' SET Grade = ' +
#IntrotoPublicSpeaking + ' Status = "Completed" WHERE Course = 7600105';
EXEC sp_executesql #sql;
END
GO
I know that global variable works, I have another line of code that's just a MessageBox displaying the value and it's correct. Just can't get those last few lines of SQL to work. I'm trying out just this first part, #IntrotoPublicSpeaking, before I move onto the other 2.
Any help would be really appreciated.
Two things here:
DECLARE #sql as nvarchar(max)
SET #sql = 'UPDATE ' + #Username + ' SET Grade = ' +
#IntrotoPublicSpeaking + ' Status = "Completed" WHERE Course = 7600105';
EXEC sp_executesql #sql;
Missing comma before Status and I think you do need to use single quotes
DECLARE #sql as nvarchar(max)
SET #sql = 'UPDATE ' + #Username + ' SET Grade = ' +
#IntrotoPublicSpeaking + ', Status = ''Completed'' WHERE Course = 7600105';
EXEC sp_executesql #sql;
i have a simple sp in sql as bellow :
alter proc sptest(#val nvarchar(30))
as
select COUNT(*) from AAtable
where name = #val
as i call this sp with #val = 'مریم', it works well and returns value.
but when i change it like this :
alter proc sptest(#val nvarchar(30))
as
declare #q nvarchar(max)
set #q = 'select COUNT(*) from AAtable where name = ' + #val
Execute(#q)
and call it with the same #val, it converts #val value to "?" and returns error. i should say that #val comes from a string parameter in c#. as i know .net convert string to nvarchar parameter form sql. anyway i can not add N before #val.
and also i HAVE to make a string query and execute it so i can not change it to the first code too.
if i do this : set #q = 'select COUNT(*) from AAtable where name = N''' + #val + '''' it does not work too.
why execute string makes my nvarchar parameter to "?" !?
Add the N in front of your text, so it is an NVARCHAR literal, not a VARCHAR, like this: N'My Text'
Try marking the first string of your concatenation operation as explicit Unicode:
set #q = N'select COUNT(*) from AAtable where name = ' + #val
This should keep your #val in Unicode as well.
ALTER proc sptest(#val nvarchar(30))
AS
DECLARE #retval INT
DECLARE #SQLString nvarchar(500);
DECLARE #ParmDefinition nvarchar(500);
SET #SQLString =
N'select #retvalOUT = COUNT(*) from AAtable where name = #Name';
SET #ParmDefinition = N'#Name varchar(30), retvalOUT int OUTPUT';
EXECUTE sp_executesql #SQLString, #ParmDefinition,
#Name = #val,
#retvalOUT=#retval OUTPUT;
SELECT #retval;