Query returning rows in SQLServer but returns no row in VB.Net app - sql-server

I've got a big problem with my VB.Net app :
I have a query who works perfectly in SSMS, returning 16 rows.
But when I try to execute it in my VB.Net app, I've got no rows.
Here's my code who works perfecty for filling all other DataTable of my VB.Net app (more than 200 tables). In this case, variable "a_strRequete" contains the query who works well in SQLServer, returning 16 rows.
Dim v_rrqAdapteur As SqlDataAdapter
v_rrqAdapteur = New SqlDataAdapter(a_strRequete, m_cnxSQL)
v_rrqAdapteur.SelectCommand.CommandTimeout = 900
v_rrqAdapteur.SelectCommand.CommandType = CommandType.Text
o_rrqTable = New DataTable
v_rrqAdapteur.Fill(o_rrqTable)
v_rrqAdapteur.Dispose()
But when I execute this in debug, the line "v_rrqAdapteur.Fill(o_rrqTable)" is executed without any errors, but give me no row. Its driving me crazy because there's no logic in this behaviour : if a query returns rows in SSMS, it must also return the same number of rows when called from VB.Net.
The only query who have this problem is using "pivot" instruction in SQLServer code. Perhaps the problem's coming from that ?
Here's the subquery who contains the pivot in my query :
select id_pk, id_fk, [1.00], [1.25], [1.5]
from (
select
id_pk,
id_fk,
NumericField,
h_occ
from [previous subquery]
) As Hpv
pivot (sum(h_occ) for NumericField in(
[1.00], [1.25], [1.5]
)) As Spv
At the beginning, it was a stored procedure I've integrated to my custom DataSet. But when I see it was returning no rows in my app, I've taken the code of this stored procedure to execute it like a full text query in my code (using the code shown here), and it returns always no rows.
I've got only one server and only one DataBase, who contains all stored procedure, views and functions I need, and only one connection to this DataBase.
These's no CRM used in my code.
Thanks to all who will help.

So, I find a solution et now know from where this problem comes : it comes from the "pivot" instruction.
I've replace the pivot instruction by left join on sum subquery and it now works.
So, seems like the "pivot" instruction cannot be used in query executed from VB.Net app.
This is sad because the "pivot" instruction is very useful et quick to execute (much faster than a left join for every value of the variable to agregate).
Does somebody knows something about the use of "pivot" instruction used in queries executed from VB.Net app ?

Related

MSSQL record and display all languages in table including English, Chinese and Arabic [duplicate]

I am very new to working with databases. Now I can write SELECT, UPDATE, DELETE, and INSERT commands. But I have seen many forums where we prefer to write:
SELECT empSalary from employee where salary = #salary
...instead of:
SELECT empSalary from employee where salary = txtSalary.Text
Why do we always prefer to use parameters and how would I use them?
I wanted to know the use and benefits of the first method. I have even heard of SQL injection but I don't fully understand it. I don't even know if SQL injection is related to my question.
Using parameters helps prevent SQL Injection attacks when the database is used in conjunction with a program interface such as a desktop program or web site.
In your example, a user can directly run SQL code on your database by crafting statements in txtSalary.
For example, if they were to write 0 OR 1=1, the executed SQL would be
SELECT empSalary from employee where salary = 0 or 1=1
whereby all empSalaries would be returned.
Further, a user could perform far worse commands against your database, including deleting it If they wrote 0; Drop Table employee:
SELECT empSalary from employee where salary = 0; Drop Table employee
The table employee would then be deleted.
In your case, it looks like you're using .NET. Using parameters is as easy as:
string sql = "SELECT empSalary from employee where salary = #salary";
using (SqlConnection connection = new SqlConnection(/* connection info */))
using (SqlCommand command = new SqlCommand(sql, connection))
{
var salaryParam = new SqlParameter("salary", SqlDbType.Money);
salaryParam.Value = txtMoney.Text;
command.Parameters.Add(salaryParam);
var results = command.ExecuteReader();
}
Dim sql As String = "SELECT empSalary from employee where salary = #salary"
Using connection As New SqlConnection("connectionString")
Using command As New SqlCommand(sql, connection)
Dim salaryParam = New SqlParameter("salary", SqlDbType.Money)
salaryParam.Value = txtMoney.Text
command.Parameters.Add(salaryParam)
Dim results = command.ExecuteReader()
End Using
End Using
Edit 2016-4-25:
As per George Stocker's comment, I changed the sample code to not use AddWithValue. Also, it is generally recommended that you wrap IDisposables in using statements.
You are right, this is related to SQL injection, which is a vulnerability that allows a malicioius user to execute arbitrary statements against your database. This old time favorite XKCD comic illustrates the concept:
In your example, if you just use:
var query = "SELECT empSalary from employee where salary = " + txtSalary.Text;
// and proceed to execute this query
You are open to SQL injection. For example, say someone enters txtSalary:
1; UPDATE employee SET salary = 9999999 WHERE empID = 10; --
1; DROP TABLE employee; --
// etc.
When you execute this query, it will perform a SELECT and an UPDATE or DROP, or whatever they wanted. The -- at the end simply comments out the rest of your query, which would be useful in the attack if you were concatenating anything after txtSalary.Text.
The correct way is to use parameterized queries, eg (C#):
SqlCommand query = new SqlCommand("SELECT empSalary FROM employee
WHERE salary = #sal;");
query.Parameters.AddWithValue("#sal", txtSalary.Text);
With that, you can safely execute the query.
For reference on how to avoid SQL injection in several other languages, check bobby-tables.com, a website maintained by a SO user.
In addition to other answers need to add that parameters not only helps prevent sql injection but can improve performance of queries. Sql server caching parameterized query plans and reuse them on repeated queries execution. If you not parameterized your query then sql server would compile new plan on each query(with some exclusion) execution if text of query would differ.
More information about query plan caching
Two years after my first go, I'm recidivating...
Why do we prefer parameters? SQL injection is obviously a big reason, but could it be that we're secretly longing to get back to SQL as a language. SQL in string literals is already a weird cultural practice, but at least you can copy and paste your request into management studio. SQL dynamically constructed with host language conditionals and control structures, when SQL has conditionals and control structures, is just level 0 barbarism. You have to run your app in debug, or with a trace, to see what SQL it generates.
Don't stop with just parameters. Go all the way and use QueryFirst (disclaimer: which I wrote). Your SQL lives in a .sql file. You edit it in the fabulous TSQL editor window, with syntax validation and Intellisense for your tables and columns. You can assign test data in the special comments section and click "play" to run your query right there in the window. Creating a parameter is as easy as putting "#myParam" in your SQL. Then, each time you save, QueryFirst generates the C# wrapper for your query. Your parameters pop up, strongly typed, as arguments to the Execute() methods. Your results are returned in an IEnumerable or List of strongly typed POCOs, the types generated from the actual schema returned by your query. If your query doesn't run, your app won't compile. If your db schema changes and your query runs but some columns disappear, the compile error points to the line in your code that tries to access the missing data. And there are numerous other advantages. Why would you want to access data any other way?
In Sql when any word contain # sign it means it is variable and we use this variable to set value in it and use it on number area on the same sql script because it is only restricted on the single script while you can declare lot of variables of same type and name on many script. We use this variable in stored procedure lot because stored procedure are pre-compiled queries and we can pass values in these variable from script, desktop and websites for further information read Declare Local Variable, Sql Stored Procedure and sql injections.
Also read Protect from sql injection it will guide how you can protect your database.
Hope it help you to understand also any question comment me.
Old post but wanted to ensure newcomers are aware of Stored procedures.
My 10ยข worth here is that if you are able to write your SQL statement as a stored procedure, that in my view is the optimum approach. I ALWAYS use stored procs and never loop through records in my main code. For Example: SQL Table > SQL Stored Procedures > IIS/Dot.NET > Class.
When you use stored procedures, you can restrict the user to EXECUTE permission only, thus reducing security risks.
Your stored procedure is inherently paramerised, and you can specify input and output parameters.
The stored procedure (if it returns data via SELECT statement) can be accessed and read in the exact same way as you would a regular SELECT statement in your code.
It also runs faster as it is compiled on the SQL Server.
Did I also mention you can do multiple steps, e.g. update a table, check values on another DB server, and then once finally finished, return data to the client, all on the same server, and no interaction with the client. So this is MUCH faster than coding this logic in your code.
Other answers cover why parameters are important, but there is a downside! In .net, there are several methods for creating parameters (Add, AddWithValue), but they all require you to worry, needlessly, about the parameter name, and they all reduce the readability of the SQL in the code. Right when you're trying to meditate on the SQL, you need to hunt around above or below to see what value has been used in the parameter.
I humbly claim my little SqlBuilder class is the most elegant way to write parameterized queries. Your code will look like this...
C#
var bldr = new SqlBuilder( myCommand );
bldr.Append("SELECT * FROM CUSTOMERS WHERE ID = ").Value(myId);
//or
bldr.Append("SELECT * FROM CUSTOMERS WHERE NAME LIKE ").FuzzyValue(myName);
myCommand.CommandText = bldr.ToString();
Your code will be shorter and much more readable. You don't even need extra lines, and, when you're reading back, you don't need to hunt around for the value of parameters. The class you need is here...
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
public class SqlBuilder
{
private StringBuilder _rq;
private SqlCommand _cmd;
private int _seq;
public SqlBuilder(SqlCommand cmd)
{
_rq = new StringBuilder();
_cmd = cmd;
_seq = 0;
}
public SqlBuilder Append(String str)
{
_rq.Append(str);
return this;
}
public SqlBuilder Value(Object value)
{
string paramName = "#SqlBuilderParam" + _seq++;
_rq.Append(paramName);
_cmd.Parameters.AddWithValue(paramName, value);
return this;
}
public SqlBuilder FuzzyValue(Object value)
{
string paramName = "#SqlBuilderParam" + _seq++;
_rq.Append("'%' + " + paramName + " + '%'");
_cmd.Parameters.AddWithValue(paramName, value);
return this;
}
public override string ToString()
{
return _rq.ToString();
}
}

Running a Query with to much Raw Data

I am trying to run a query to give me the result of past incidence over a period of time. The raw data source for the query has too much data to return any of the newer information. I have tried nesting the query in an array to divide out the way the query runs, and that didn't correct the problem.
=query(IMPORTRANGE("Spread Sheet Key","Coaching Responses!A:Z"),"select Col1,Col14,Col4,Col3,Col7,Col6,Col8,Col15,Col10,Col11,Col13,Col17,Col18,Col19,Col20,Col21,Col22,Col26 where Col23 contains '"&Cover!E2&"' Order by Col1 desc",1)
I also tried this formula
=Query({Importrange("Spread Sheet Key","Coaching Responses!A:Z5000"),Importrange("Spread Sheet Key","Coaching Responses!A5001:Z")} "select Col1,Col14,Col4,Col3,Col7,Col6,Col8,Col15,Col10,Col11,Col13,Col17,Col18,Col19,Col20,Col21,Col22,Col26 where Col23 contains '"&Cover!E2&"')
The first code will not return anything past row 5000 the second code
keeps giving me a parse error.
correct formula syntax should be:
=QUERY({IMPORTRANGE("ID1", "Coaching Responses!A1:Z5000");
IMPORTRANGE("ID1", "Coaching Responses!A5001:Z")},
"select Col1,Col14,Col4,Col3,Col7,Col6,Col8,Col15,Col10,Col11,Col13,Col17,Col18,Col19,Col20,Col21,Col22,Col26
where Col23 contains '"&Cover!E2&"'")

Multi value parameter not working in SSRS report

I have a SSRS report. there is a long SQL query on the main query, in the last SELECT I want to filter the results with WHERE expression, the filter should be with a multi value parameter.
I set the parameter in this way:
Create a new Dataset with a query.
Add a new parameter to the Parameters folder (with name NewParam).
Check the "Allow multiple values" checkbox.
Add the parameter to the "Main Query" and set the value with this expression:
=Join(Parameters!NewParam.Value,",")
At the end of the Main Query I filter the results:
select *
from #FinalStatusTbl
where Test_Number in (#NewParam)
order by Priority
The problem is:
On the report when I choose one value from the list I got expected results, but If I choose multi values the results are empty (not got an error.)
Do you have any idea why?
(When I try this: where Test_Number in ('Test 1', 'Test 2') it works well).
When you create a dataset with a sql query, multi valued parameters work with the in(#ParamName) without any changes.
Replace your =Join(Parameters!NewParam.Value,",") with just =Parameters!NewParam.Value and you should be fine.
That said, the reason you see people using that join expression is because sometimes your query will slow down considerably if your parameter has a lot of potential selections and you data is reasonably large. What is done here is to combine the join expression with a string splitting function in the dataset that converts the resulting Value1,Value2,Value3 string value in a table that can be used in the query via inner join.
This is also a requirement if passing multiple values as a parameter to a stored procedure, as you can't use the in(#ParamName) syntax.
You could try taking the parameter out of the where clause and use the parameter in the filters section of the dataset properties.
This will effectively shift the filtering from the SQL to SSRS.
What you need to do is split your string in the database. What is being passed to your query is 'Test 1, Test 2' as a complete string, NOT 'Test 1' and 'Test 2'. This is why a single value works, and multiple values do not.
Here is a really good link on how to split strings, in preparation for your scenario. The function I most often use is the CTE example, which returns a table of my split strings. Then I change my SQL query to use IN on the returned table.
In your example, you will want to write WHERE Test_Number IN (SELECT Item FROM dbo.ufn_SplitStrings(#NewParam) , where ufn_SplitString is the function you create from the link previously mentioned.
This is what I did and it works well to me. You can try it also.
=sum(if(Fields!Business_Code.Value = "PH"
and (Fields!Vendor_Code.Value = "5563"
and Fields!Vendor_Code.Value = "5564"
and Fields!Vendor_Code.Value = "5565"
and Fields!Vendor_Code.Value = "5551")
, Fields!TDY_Ordered_Value.Value , nothing ))

SSRS: Passing/Setting parameter to Dataset using Expression

I am using Microsoft SQL Server Report Builder 3.0. I have created a Stored Procedure (stored_procedure1) in the database which has a Parameter (parameter1). Here, stored_procedure1 returns result1.
Then, I used stored_procedure1 to create a Dataset (dataset1) in the Microsoft SQL Report Builder 3.0. Next, I created a Table (table1) in Microsoft SQL Report Builder 3.0 with 2 rows and 2 columns (total 4 cells).
I would like to fill each element of table1 with result1 from dataset1. Hence, I set expression of each cell of table1 as follows:
=Sum(Fields!result1.Value, "dataset1")
When I run this report, it works perfectly and asks me to enter parameter1. However, I want to use single Dataset (dataset1) with different values of parameter1 for each cell of the table. Hence, I want to pass/set parameter1 with unique parameter_value for each expression of table cells. Say I want to set parameter1 = parameter_value1 for first cell.
For example, if I need to set parameter_value = 5, I did something like
=Sum(Fields!result1.Value, "dataset1"), Parameters!parameter1.Value = 5
I also tried following:
=Sum(Fields!result1.Value, "dataset1") & Parameters!parameter1.Value = 5.
It doesn't work.
In summary, I coudln't pass or set parameter value together with an expression.
Can we set/parameter value.
I would like to thank you in advance.
If anyone got stuck with this problem, I found a way around for this. T
here is no way one can pass parameter within expression.
You will need to create a subreport to do this. You can pass parameter to subreport.
Its little time consuming. However, it seems there is no other way around.

ColdFusion 10 error with Stored Procedures

In a .CFC file, within a CFfunction and with CFargument tags.
<cfscript>
var sp=new storedproc();
sp.setDatasource(variables.datasource);
sp.setProcedure("storedProcedure_INSERT");
sp.addParam(cfsqltype="cf_sql_integer",type="in",value=arguments.one);
sp.addParam(cfsqltype="cf_sql_integer",type="in",value=arguments.two);
sp.addParam(cfsqltype="cf_sql_integer",type="in",value=arguments.three);
sp.addParam(cfsqltype="cf_sql_integer",type="in",value=arguments.four);
sp.addProcResult(name="results",resultset=1);
//writeDump(sp);break; //This dump is reached
var spObj=sp.execute(); //blows up here; this is never reached
writeDump(spObj);break; //This is never reached, either.
var spResults=spObj.getProcResultSets().results;
A shiny nickle to anyone who can tell me why the sp.execute() is blowing up with message
"Cannot find results key in structure.
The specified key, results, does not exist in the structure."
I've used this psuedo-code many, may times in the past, and never had it do this. I'm connected to a MSSQL Server 2012 DB, everything's cricket in CF Admin, and other SPs are working properly. The stack trace doesn't even include any of MY code at all o_O
The error occurred in C:/ColdFusion10/cfusion/CustomTags/com/adobe/coldfusion/base.cfc: line 491
Called from C:/ColdFusion10/cfusion/CustomTags/com/adobe/coldfusion/storedproc.cfc: line 142
Called from //hq-devfs/development$/websites/myProject/cfc/mySOAPWSDLs.cfc: line 123
And SO is blowing up if I try and paste anymore of that. Google has...not been helpful ._.
Short answer: The error means you are trying to retrieve a resultset from the stored procedure, when it does not actually return one. A simple solution is to add a SELECT to the end of your procedure, so it returns a resultset containing the data you need. Then your original code will work:
SELECT ##ROWCOUNT AS NumOfRowsAffected;
Longer answer:
The method you are using, addProcResult(), is the equivalent of <cfprocresult>. It is intended to capture a resultset returned from a stored procedure. (Due to CF's poor choice of attribute names, a lot of people think "resultset" means the storedproc "result" structure, but they are two totally different things). A "resultset" is a query object", in CF parlance.
While all four (4) of the primary sql statements return some result, not all of them return a "query object"
Only SELECT statements generate a "query object"
INSERT/UPDATE/DELETE statements simply return the number of rows affected. They do not generate a "query object".
Since your stored procedure performs an INSERT, it does not generate a "query object". Hence the error when you try and grab the non-existent query here:
sp.addProcResult(name="results",resultset=1);
The simple solution is to add a SELECT statement to the end of your stored procedure, so that it does return a query object. Then your code will work as expected.
As an aside, I suspect you were actually trying to grab the "result" structure, but used the wrong method. The equivalent of <cfstoredproc result=".."> is getPrefix(). Though that would not work here anyway. According to the docs, it does not contain the number of rows affected. Probably because stored procedures can execute multiple statements, each one potentially returning a row count, so there is not just a single value to return.

Resources