SQL execute string issue with National language character? - c#

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;

Related

SqlCommand Parameters.AddWithValue return # instead of variable [duplicate]

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

PROCEDURE Return always 0 for string statement

I have a procedure that can be changed dynamically by user for multi column and I write it in SQL when I run it. Everything is OK in SQL and Server Explorer in Visual Studio but when I want use it in C# and call it, it just return 0 always.
Can anybody help me?!
CREATE PROCEDURE [dbo].[PDaynamicActualBy2Column]
#Colname1 nvarchar(100),
#VarCol1 nvarchar(100),
#Colname2 nvarchar(100),
#VarCol2 nvarchar(100),
#VarWeekNum nvarchar(100)
as
DECLARE #temp nvarchar(1500)
set #temp='SELECT SUM([dbo].[WeekActualTemp].[ACTUAL]) from [dbo].[MAINTB] join [dbo].[WeekActualTemp] on [dbo].[MAINTB].[UQ]=[dbo].[WeekActualTemp].[UQ]
where [dbo].[WeekActualTemp].[WeekNO]='+#VarWeekNum+' And [dbo].[MAINTB].'+#Colname1+' = '''+#VarCol1+''' And [dbo].[MAINTB].'+#Colname2+' = '''+#VarCol2+''''
exec (#temp)
This does not address the problem in the C#, however, it does address the huge injection issue you have in your code. Like mentioned, don't inject your parameters and properly quote your dynamic object names. This results in something like the below:
CREATE PROC dbo.PDaynamicActualBy2Column #Colname1 sysname, #VarCol1 nvarchar(100), #Colname2 sysname, #VarCol2 nvarchar(100), #VarWeekNum int AS --Assumed #VarWeekNum is an int, as why else is it called "num"?
BEGIN
DECLARE #SQL nvarchar(MAX),
#CRLF nchar(2) = NCHAR(13) + NCHAR(10);
SET #SQL = N'SELECT SUM(WAT.Actual) AS ActualSum' + #CRLF +
N'FROM dbo.MAINTB MTB' + #CRLF +
N' JOIN dbo.WeekActualTemp WAT ON MTB.UQ = WAT.UQ' + #CRLF +
N'WHERE WAT.WeekNO = #VarWeekNum' + #CRLF +
N' AND MTD.' + QUOTENAME(#Colname1) + N' = #VarCol1' + #CRLF +
N' AND MTD.' + QUOTENAME(#Colname2) + N' = #VarCol2;';
--PRINT #SQL; Your Best Friend
EXEC sp_executesql #SQL, N'#VarCol1 nvarchar(100),#VarCol2 nvarchar(100),#VarWeekNum int', #VarCol1, #VarCol2, #VarWeekNum;
END;
GO
Because you're only returning a single scalar value, you could also use an OUTPUT parameter as well, instead of a SELECT to the display the value. This would look like the below:
CREATE PROC dbo.PDaynamicActualBy2Column #Colname1 sysname, #VarCol1 nvarchar(100), #Colname2 sysname, #VarCol2 nvarchar(100), #VarWeekNum int, #ActualSum int OUTPUT AS --Assumes Actual is an int in your table. Use an appropriate data type
BEGIN
DECLARE #SQL nvarchar(MAX),
#CRLF nchar(2) = NCHAR(13) + NCHAR(10);
SET #SQL = N'SELECT #ActualSum = SUM(WAT.Actual)' + #CRLF +
N'FROM dbo.MAINTB MTB' + #CRLF +
N' JOIN dbo.WeekActualTemp WAT ON MTB.UQ = WAT.UQ' + #CRLF +
N'WHERE WAT.WeekNO = #VarWeekNum' + #CRLF +
N' AND MTD.' + QUOTENAME(#Colname1) + N' = #VarCol1' + #CRLF +
N' AND MTD.' + QUOTENAME(#Colname2) + N' = #VarCol2;';
--PRINT #SQL; Your Best Friend
EXEC sp_executesql #SQL, N'#VarCol1 nvarchar(100),#VarCol2 nvarchar(100),#VarWeekNum int, #ActualSum int OUTPUT', #VarCol1, #VarCol2, #VarWeekNum, #ActualSum OUTPUT; --Again, assumes Actual is an int.
END;
GO
Notice, as mentioned in the comments, I get rid of the 3+ part naming for your columns, and alias your tables instead. I then use those aliases to reference to correct object. I've also put "Your best Friend" in the code, should you need to debug it.
Note: As mentioned in a different answer, zero is likely because the SP is returning 0 to mean success. This is a documented and intentional feature of Stored Procedures:
Unless documented otherwise, all system stored procedures return a value of 0. This indicates success and a nonzero value indicates failure.
As the SP above is likely successful, the RETURN value is 0; to denote success. You shouldn't be looking at the RETURN value, but the dataset, or in the latter example the OUTPUT parameter's value. I am sure there are questions on SO for how to use an OUTPUT parameter in linq.
Zero in return value of your stored procedure means it executed successfully.
You should return a value by "RETURN" statement or "SELECT" statement for table in return.
In LINQ you cannot call an SP that have a meta output that is dynamic, you have to write your SP with "select" output and make a model and then go to SP and edit it again.
Alter PROCEDURE [dbo].[PDaynamicActualBy2Column]
#Colname1 nvarchar(100),
#VarCol1 nvarchar(100),
#Colname2 nvarchar(100),
#VarCol2 nvarchar(100),
#VarWeekNum nvarchar(100)
as
DECLARE #temp nvarchar(1500)
set #temp='SELECT SUM([dbo].[WeekActualTemp].[ACTUAL]) from [dbo].[MAINTB] join [dbo].[WeekActualTemp] on [dbo].[MAINTB].[UQ]=[dbo].[WeekActualTemp].[UQ]
where [dbo].[WeekActualTemp].[WeekNO]='+#VarWeekNum+' And [dbo].[MAINTB].'+#Colname1+' = '''+#VarCol1+''' And [dbo].[MAINTB].'+#Colname2+' = '''+#VarCol2+''''
-- exec (#temp)
SELECT top 0
SUM([dbo].[WeekActualTemp].[ACTUAL]) as sum
from [dbo].[MAINTB] join [dbo].[WeekActualTemp] on [dbo].[MAINTB].[UQ]=[dbo].[WeekActualTemp].[UQ]
then import SP in your LINQ then comment "select" and uncomment "exec" .

How do I get the correct sql quoted string for a .NET DbType

I want to run an ALTER TABLE that adds a default value constraint to a column.
I generate this statement dynamically from a .NET program.
How do I best format and quote the value when building my sql - now that ALTER TABLE statements does not support parameters (Gives the error 'Variables are not allowed in the ALTER TABLE statement').
Is there a utility for that in .NET? Or another solution?
You can do this in TSQL; for example, say you parameterize the command, passing in #DefaultValue, a varchar which may or may not be a valid TSQL literal. Because we are writing DDL, we will need to concatenate and exec, however we clearly don't want to blindly concatenate, as the value could be illegal. Fortunately, quotename does everything we need. By default, quotename outputs [qualified object names], but you can tell it to operate in literal escaping mode, for both single-quote and double-quote literals.
So our query that accepts #DefaultValue can build an SQL string:
declare #sql nvarchar(4000) = 'alter table ...';
-- ... blah
-- append the default value; note the result includes the outer quotes
#sql = #sql + quotename(#DefaultValue, '''');
-- ... blah
exec (#sql);
Full example:
--drop table FunkyDefaultExample
create table FunkyDefaultExample (id int not null)
declare #tableName varchar(20) = 'FunkyDefaultExample',
#colName varchar(20) = 'col name',
#defaultValue varchar(80) = 'test '' with quote';
-- the TSQL we want to generate to exec
/*
alter table [FunkyDefaultExample] add [col name] varchar(50) null
constraint [col name default] default 'test '' with quote';
*/
declare #sql nvarchar(4000) = 'alter table ' + quotename(#tablename)
+ ' add ' + quotename(#colName) + 'varchar(50) null constraint '
+ quotename(#colName + ' default') + ' default '
+ quotename(#defaultValue, '''');
exec (#sql);
-- tada!
string.Format("alter table YourTable add constraint DF_YourTable_Col1 default '{0}'",
inputValue.Replace("'", "''"));

Take value from exec sp_executesql in stored procedure

declare #nopqty decimal(10,2)
declare #ntotamt decimal(10,2)
declare #npartno nvarchar(20)
SET #Orgcd =101
SET #npartno = "A 0001 150"
declare #qry nvarchar(4000)
SET #qry = 'SELECT #nopqty = oqty' + convert(varchar(3), #norgcd) +
', #ntotamt = ocost' + convert(varchar(3), #norgcd) +
' FROM stock WHERE part = #npartno'
exec sp_executesql #qry
Error
Must declare the scalar variable
Then I used
exec sp_executesql #qry, N'#nopqty decimal(10,2),#ntotamt decimal(10,2),#npartno nvarchar(20)',#nopqty=#nopqty,#ntotamt=#ntotamt,#npartno=#npartno
but when print #nopqty, #ntotamt it is null
How can I take out #nopqty, #ntotamt from these #qry?
I need these value for some calculation
Specify the parameter as output. For example:
declare #name varchar(10)
exec sp_executesql
N'select top 1 #name = name from sys.tables',
N'#name varchar(10) output',
#name = #name output
print #name

Adapter Unable to fill data in dataset: Exception thrown

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

Categories

Resources