How to create RDLC report from dynamic query in SQL Server Express - sql

I can't create the rdlc report from this procedure, I'm using report viewer but when I select the procedure, it doesn't show any column names but my procedure returns 7 columns. How can I create the report please help ? I'm creating the report in vb.net
ALTER PROCEDURE Pr_getAcceptedOnDateReport
#date date
AS
SET FMTONLY OFF
DECLARE #SQL varchar(MAX)
DECLARE #antiHIV bit
DECLARE #HBsAg bit
DECLARE #IGMHBCore bit
DECLARE #NAT bit
DECLARE #Malaria bit
DECLARE #TotalHBCore bit
DECLARE #Syphilis bit
DECLARE #HCV bit
DECLARE #ICT bit
DECLARE #DCT bit
DECLARE #Antibody bit
Select #antiHIV=[HIV1/2 screen Reactive],
#IGMHBCore=[IgM HBcore Reactive],
#HBsAg=[HBsAg Screen Reactive],
#NAT= [NAT Reactive],
#Malaria=[Malaria Screen Reactive],
#TotalHBCore=[Total HBcore Reactive],
#Syphilis=[Syphilis Screen Reactive],
#HCV=[HCV screen Reactive],
#ICT=[ICT Positive],
#DCT= [DCT Positive],
#Antibody= [Antibody Screen Positive]
from m_rejectionRules where deleted=0
DECLARE #sql1 nvarchar(4000)
Select #sql1='Select t.donorid, t.donorname, t.sampleid, t.customid,t.bagtype,t.bagnumber, t.segmentno from ttidetail t, m_donor m
where t.donorid=m.donorid
AND CONVERT(date, m.RDate) =''' + cast(#date as varchar(100)) + ''''
IF #antiHIV='True'
BEGIN
SELECT #sql1 = #sql1 + ' AND t.antiHIV like ' + ''''+ 'Non%Reactive'+''''
END
IF #HBsAg='True'
BEGIN
SELECT #sql1 = #sql1 + ' AND t.HBsAg like '+ ''''+ 'Non%Reactive'+''''
END
IF #IGMHBCore='True'
BEGIN
SELECT #sql1 = #sql1 + ' AND t.IGM_antiHBC like '+ ''''+ 'Non%Reactive'+''''
END
IF #NAT='True'
BEGIN
SELECT #sql1 = #sql1 + ' AND t.NAT_HIV1 like '+ ''''+ 'Non%Reactive'+''''
END
IF #Malaria='True'
BEGIN
SELECT #sql1 = #sql1 + ' AND t.malariaScreen like '+ ''''+ 'Non%Reactive'+''''
END
IF #TotalHBCore='True'
BEGIN
SELECT #sql1 = #sql1 + ' AND t.totalAnti_HBC like '+ ''''+ 'Non%Reactive'+''''
END
IF #Syphilis='True'
BEGIN
SELECT #sql1 = #sql1 + ' AND t.SyphilisScreen like '+ ''''+ 'Non%Reactive'+''''
END
EXEC sp_executesql #sql1

Create a class which maps to your fields returned by your stored procedure
Public Class ReportData
Property donorid AS Integer = 0
Property donorname as string = string.empty
Property sampleid as integer = 0
Property customid as integer = 0
Property bagtype as string = string.empty
Property bagnumber as integer = 0
Property segmentno as integer = 0
End Class
Assuming that you have a function which returns a dataset using the above query, I will refer to it as ds
* MOST IMPORTANT *
When creating your rdlc report instead of mapping to the storedprocdure map it to an object datasource and select the class you just created. Use the fileds in this class as fields for your report.
In the button show report you can use the following code to display your report
Private Sub ShowReport()
Dim dsL As DataSet = New DataSet()
dsL = GetReportData() ' Function which will get the data from the SQL Query
Dim rds As ReportDataSource = New ReportDataSource()
rds.Name = "ReportDS" ' Change to what you will be using when creating an objectdatasource
rds.Value = dsL.Tables(0)
With rvReport ' Name of the report control on the form
.Reset()
.ProcessingMode = ProcessingMode.Local
.LocalReport.DataSources.Clear()
.Visible = True
.LocalReport.ReportPath = reportPath
.LocalReport.DataSources.Add(rds)
' If you have any parameters you can pass them here
Dim rptParameters As New List(Of ReportParameter)()
With rptParameters
.Add(New ReportParameter("Title",
String.Format("{0} Grid For Period {1} To {2}",
gridType,
FormatDateTime(startDate, DateFormat.ShortDate),
FormatDateTime(endDate, DateFormat.ShortDate))))
.Add(New ReportParameter("SubTitle", String.Format("Program: {0}", ucProgram.Text)))
.Add(New ReportParameter("StartDate", startDate))
.Add(New ReportParameter("EndDate", endDate))
End With
.LocalReport.SetParameters(rptParameters)
.RefreshReport()
End With
End Sub

Related

Search a string in whole mysql database

I wrote this query for searching a string in whole database . Earlier it was working properly now it doesn't fetch full result at all . I don't get what is wrong with this query . Please help
QUERY
/*
- Search through tables to find specific text
- Written by Luis Chiriff (with help from SQL Server Central)
- luis.chiriff#gmail.com # 24/11/2008 # 11:54
*/
-- Variable Declaration
Declare #StringToFind VARCHAR(200), #Schema sysname, #Table sysname, #FullTable int, #NewMinID
int, #NewMaxID int,
#SQLCommand VARCHAR(8000), #BaseSQLCommand varchar(8000), #Where VARCHAR(8000), #CountCheck
varchar(8000) , #FieldTypes varchar(8000),
#cursor VARCHAR(8000), #columnName sysname, #SCn int, #SCm int
Declare #TableList table (Id int identity(1,1) not null, tablename varchar(250))
Declare #SQLCmds table (id int identity(1,1) not null, sqlcmd varchar(8000))
Declare #DataFoundInTables table (id int identity(1,1) not null, sqlcmd varchar(8000))
-- Settings
SET #StringToFind = 'abcdef'
SET NOCOUNT ON
SET #StringToFind = '%'+#StringToFind+'%'
-- Gathering Info
if ((select count(*) from sysobjects where name = 'tempcount') > 0)
drop table tempcount
create table tempcount (rowsfound int)
insert into tempcount select 0
-- This section here is to accomodate the user defined datatypes, if they have
-- a SQL Collation then they are assumed to have text in them.
SET #FieldTypes = ''
select #FieldTypes = #FieldTypes + '''' + rtrim(ltrim(name))+''',' from systypes where collation
is not null or xtype = 36
select #FieldTypes = left(#FieldTypes,(len(#FieldTypes)-1))
insert into #TableList (tablename)
select name from sysobjects
where xtype = 'U' and name not like 'dtproperties'
order by name
-- Start Processing Table List
select #NewMinID = min(id), #NewMaxID = max(id) from #TableList
while(#NewMinID <= #NewMaxID)
Begin
SELECT #Table = tablename, #Schema='dbo', #Where = '' from #TableList where id = #NewMinID
SET #SQLCommand = 'SELECT * FROM ' + #Table + ' WHERE'
-- removed ' + #Schema + '.
SET #cursor = 'DECLARE col_cursor CURSOR FOR SELECT COLUMN_NAME
FROM [' + DB_NAME() + '].INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = ''' + #Schema + '''
AND TABLE_NAME = ''' + #Table + '''
AND DATA_TYPE IN ('+#FieldTypes+')'
--Original Check, however the above implements user defined data types --AND DATA_TYPE IN
(''char'',''nchar'',''ntext'',''nvarchar'',''text'',''varchar'')'
EXEC (#cursor)
SET #FullTable = 0
DELETE FROM #SQLCmds
OPEN col_cursor
FETCH NEXT FROM col_cursor INTO #columnName
WHILE ##FETCH_STATUS = 0
BEGIN
SET #Where = #Where + ' [' + #columnName + '] LIKE ''' + #StringToFind + ''''
SET #Where = #Where + ' OR'
--PRINT #Table + '|'+ cast(len(isnull(#Where,''))+len(isnull(#SQLCommand,'')) as varchar(10))+'|'+#Where
if (len(isnull(#Where,''))+len(isnull(#SQLCommand,'')) > 3600)
Begin
SELECT #Where = substring(#Where,1,len(#Where)-3)
insert into #SQLCmds (sqlcmd) select #Where
SET #Where = ''
End
FETCH NEXT FROM col_cursor INTO #columnName
END
CLOSE col_cursor
DEALLOCATE col_cursor
if (#Where <> '')
Begin
SELECT #Where = substring(#Where,1,len(#Where)-3)
insert into #SQLCmds (sqlcmd)
select #Where --select #Table,count(*) from #SQLCmds
End
SET #BaseSQLCommand = #SQLCommand
select #SCn = min(id), #SCm = max(id) from #SQLCmds
while(#SCn <= #SCm)
Begin
select #Where = sqlcmd from #SQLCmds where ID = #SCn
if (#Where <> '')
Begin
SET #SQLCommand = #BaseSQLCommand + #Where
SELECT #CountCheck = 'update tempcount set rowsfound = (select count(*) '+ substring(#SQLCommand,10,len(#SQLCommand)) + ')'
EXEC (#CountCheck)
if ((select rowsfound from tempcount) > 0)
Begin
PRINT '--- ['+cast(#NewMinID as varchar(15))+'/'+cast(#NewMaxID as varchar(15))+'] '+#Table + ' ----------------------------------[FOUND!]'
--PRINT '--- [FOUND USING:] ' +#SQLCommand
insert into #DataFoundInTables (sqlcmd) select #SQLCommand
EXEC (#SQLCommand)
update tempcount set rowsfound = 0
End
else
Begin
PRINT '--- ['+cast(#NewMinID as varchar(15))+'/'+cast(#NewMaxID as varchar(15))+'] '+#Table
End
End
SET #SCn = #SCn + 1
End
set #NewMinID = #NewMinID + 1
end
if ((select count(*) from sysobjects where name = 'tempcount') > 0)
drop table tempcount
/*
This will now return all the sql commands you need to use
*/
select #NewMinID = min(id), #NewMaxID = max(id) from #DataFoundInTables
if (#NewMaxID > 0)
Begin
PRINT ' '
PRINT ' '
PRINT '-----------------------------------------'
PRINT '----------- TABLES WITH DATA ------------'
PRINT '-----------------------------------------'
PRINT ' '
PRINT 'We found ' + cast(#NewMaxID as varchar(10)) + ' table(s) with the string '+#StringToFind
PRINT ' '
while(#NewMinID <= #NewMaxID)
Begin
select #SQLCommand = sqlcmd from #DataFoundInTables where ID = #NewMinID
PRINT #SQLCommand
SET #NewMinID = #NewMinID + 1
End
PRINT ' '
PRINT '-----------------------------------------'
End
This query was working fine one month ago but now it doesn't fetch the results . Can anyone tell me what is wrong in this query .

SQL with AND statements, dynamically building up

Aim: I'm building a dynamic SQL string and want to make the search an AND function
Code type: SQL stored procedure within SQL Server Management Studio
Issue: If the first search is not required then I need to know this (I know because the default is '0' in this case. I feel I'm missing a sitter but don't seem to be able to stackoverflow/Google for the solution.
I set up #QueryString with a default of '' so the functionality will work.
What will fix this?:
I've thought about COALESCE and potential use of IF ELSE within the IF but I am hoping there is clean solution along the lines of
SET #QUERYSTRING = IF(#QUERYSTRING = '','', + + ' FIELD1 LIKE ''%' + LTRIM(RTRIM(#s1)) + '%' )
Current example (snippet):
ALTER PROCEDURE [dbo].[spGridSearchTest]
#s1 NVARCHAR(20),
#s2 VARCHAR(20)
AS
BEGIN
DECLARE #QUERY NVARCHAR(MAX) = ''
DECLARE #QUERYSTRING NVARCHAR(MAX) = ''
SET #QUERY = 'SELECT * FROM TblTable'
IF #s1 <> '1234xyz'
SET #QUERYSTRING = #QUERYSTRING + ' Field1 LIKE ''%' + LTRIM(RTRIM(#s1)) + '%'
IF #s2 <> '1234xyz'
SET #QUERYSTRING = #QUERYSTRING + ' Field2 LIKE ''%' + LTRIM(RTRIM#s2)) + '%'
IF LEN(LTRIM(RTRIM(#QUERYSTRING))) > 0
SET #QUERY = LTRIM(RTRIM(#QUERY)) + ' WHERE ' + LTRIM(RTRIM(#QUERYSTRING)) + ''''
EXECUTE(#QUERY)
END
If I understand better your issue:
Try this:
ALTER PROCEDURE [dbo].[spGridSearchTest]
#s1 NVARCHAR(20),
#s2 VARCHAR(20)
AS
BEGIN
DECLARE #QUERY NVARCHAR(MAX) = ''
DECLARE #QUERYSTRING NVARCHAR(MAX) = ''
DECLARE #conditionadded char(1) = 'N'
SET #QUERY = 'SELECT * FROM TblTable'
IF #s1 <> '1234xyz'
BEGIN
SET #QUERYSTRING = ' Field1 LIKE ''%' + LTRIM(RTRIM(#s1)) + '%'
SET #conditionadded = 'Y'
END
IF #s2 <> '1234xyz'
BEGIN
IF (#conditionadded = 'Y')
BEGIN
SET #QUERYSTRING = #QUERYSTRING + ' AND '
END
SET #QUERYSTRING = #QUERYSTRING + ' Field2 LIKE ''%' + LTRIM(RTRIM#s2)) + '%'
SET #conditionadded = 'Y'
END
IF (#conditionadded = 'Y')
BEGIN
SET #QUERY = LTRIM(RTRIM(#QUERY)) + ' WHERE ' + LTRIM(RTRIM(#QUERYSTRING)) + ''''
END
EXECUTE(#QUERY)
END
Do you really need a dynamic query? Why not use something like this:
select
Whatever
from MyTable
where
(#s1 = '1234xyz' or Field1 = #s1)
and
(#s2 = '1234xyz' or Field2 = #s2)
This avoids a security hole, and depending on your query patterns and data set, it might even be faster. And of course, it's pretty easy to read, and you don't have to deal with SQL in strings :)

Parametrize query in t-sql

SELECT TOP #columnCount #columnName
FROM #tableName
I get the following error
Incorrect syntax near '#columnCount'.
What could be wrong?
If I change to
SELECT TOP (#columnCount) #columnName
FROM #tableName
I get the following error
Must declare the table variable "#tableName".
I run it from C#
A safe and secure way would be
DECLARE #columnCount INT = 100
DECLARE #columnName NVARCHAR(128) = 'YourColumnName'
DECLARE #tableName NVARCHAR(128) = 'YourTableName'
DECLARE #Sql NVARCHAR(MAX);
SET #Sql = N'SELECT TOP (#columnCount) ' + QUOTENAME(#columnName) + N'
FROM ' + QUOTENAME(#tableName)
EXECUTE sp_executesql #Sql
,N'#columnCount INT'
,#columnCount
You need dynamic SQL to accomplish what you're trying to do.
DECLARE #sql VARCHAR(max);
SET #sql = 'SELECT TOP ' + #columnCount + ' ' + #columnName + ' FROM ' + #tableName;
EXEC(#sql);
The variables used need to be converted appropriately.
Read more in the documentation
Column lists and Table names cannot be parameters. However, since you are running this from C# you are technically already using Dynamic SQL (unless you are calling a stored procedure with those params but there is no mention here of stored procedures being used so for now I will assume not). When building the SQL in C#, you need to concatenate the Column List and Table Name into the query but you can still use a parameter for the value used by the TOP() operator:
SqlConnection _Connection = new SqlConnection("connection string");
SqlCommand _Command = new SqlCommand();
SqlDataReader _Reader = null;
string _Query;
string _TableName = "dbo.MyTable";
string _ColumnList = "Field1, Field2 AS [AliasedName], Field3";
int _NumberOfRows = 12;
_Query = String.Concat("SELECT TOP (#NumberOfRows) ",
_ColumnList, " FROM ", _TableName);
SqlParameter _NumRows = new SqlParameter("#NumberOfRows", SqlDbType.Int);
_NumRows.Value = _NumberOfRows;
try
{
_Connection.Open();
_Reader = _Command.ExecuteReader();
// do stuff
}
finally
{
_Reader.Close();
_Connection.Close();
}
Of course, you could also just concatenate the #NumberOfRows value directly into the query as well, but keeping it as a parameter will allow for Query Plan re-use if running this query multiple times with the same values for ColumnList and TableName but changing the #NumberOfRows value.

Dynamic sql stored procedure update query issue?

I've written the below code to set filepath column in my table as 'F:\DataMigration\Wise\DELTA_20121008\Attachments\SR\SR_1.txt'
where SR_1 is file_name column
.txt is file_ext column from my table.
but after executing following procedure, I'm getting filepath column in table as
'F:\DataMigration\Wise\DELTA_20121008\Attachments\file_name.file_ext'
means It's treating column names as string, how i can make it as column so it will
use values in that column.
alter procedure [dbo].[WISEMissingAttachmentReportGenerator]
(
#tablename varchar(255), #pathonlocal nvarchar(255)
)
as
begin
--step 1
exec dbo.proc_alter_table #tablename
--step 2
EXEC ('update '+ #tablename +
' set filepath = '''+ #pathonlocal + ' file_name'+'.'+'file_ext''')
EXEC('Select * from '+#tablename)
end
exec [dbo].[WISEMissingAttachmentReportGenerator] [WISE.Non_VP_Service_Request_Attachments_File_Check_Analysis],
N'F:\DataMigration\Wise\DELTA_20121008\Attachments\SR\'
Try;
EXEC('UPDATE '+ #tablename +
' SET filepath = '''+ #pathonlocal + ''' + file_name + '''+'.'+''' + file_ext')
Equal as;
UPDATE [YourTable] SET filepath = 'YourPath' + file_name + '.' + file_ext
Try changing your statement to this:
EXEC ('update '+ #tablename +
' set filepath = '''+ #pathonlocal + ''' + file_name + ''.'' + file_ext')
declare #tblnm varchar(20) = 'test'
declare #upda varchar(20) = 'update '
declare #set varchar(25) = ' set'
declare #id varchar(25) = ' id'
declare #cmd varchar(1000)
set #cmd = #upda + #tblnm + #set + #id + '=7'
exec(#cmd)
SAMPLE SQL UPDATE QUERY - FOR BUILDING TABLENAME DYNAMICALLY
EXECUTED GUYS - THIS IS CALL JUGAAAAAAAAAD [NO NEED TO GET INTO ''' STUFF]

SQL Query within VS TableAdapter Query Configuration Wizard

I am trying to write an SQL query within Visual Studio TableAdapter Query Wizard
My SQL query is:
DECLARE #SQL varchar(255);
SET #SQL = ' SELECT * FROM dbAddress WHERE 1 = 1'
IF #ApexLine1 = ''
BEGIN
SET #SQL = #SQL + ' AND addLine1 IS NULL '
END
ELSE
BEGIN
SET #SQL = #SQL + ' AND addLine1 = ''' + #ApexLine1 + ''''
END
IF #ApexLine2 = ''
BEGIN
SET #SQL = #SQL + ' AND addLine2 IS NULL '
END
ELSE
BEGIN
SET #SQL = #SQL + ' AND addLine2 = ''' + #ApexLine2 + ''''
END
IF #ApexLine3 = ''
BEGIN
SET #SQL = #SQL + ' AND addLine3 IS NULL '
END
ELSE
BEGIN
SET #SQL = #SQL + ' AND addLine3 = ''' + #ApexLine3 + ''''
END
IF #ApexZip = ''
BEGIN
SET #SQL = #SQL + ' AND addPostCode IS NULL '
END
ELSE
BEGIN
SET #SQL = #SQL + ' AND addPostCode = ''' + #ApexZip + ''''
END
IF #ApexCity = ''
BEGIN
SET #SQL = #SQL + ' AND addLine4 IS NULL '
END
ELSE
BEGIN
SET #SQL = #SQL + ' AND addLine4 = ''' + #ApexCity + ''''
END
IF #ApexProv = ''
BEGIN
SET #SQL = #SQL + ' AND addLine5 IS NULL '
END
ELSE
BEGIN
SET #SQL = #SQL + ' AND addLine5 = ''' + #ApexProv + ''''
END
EXEC(#SQL)
I get the error:
'The Declare SQL contruct or statement is not supported'
If I remove the Declare statement I get error:
'The Set SQL construct or statement is not supported'
Is there a work around for this?
Thanks.
Anything like this:
SET #SQL = #SQL + ' AND addLine1 = ''' + #ApexLine1 + ''''
is EVIL. Don't do it. Variables like #ApexLine1 could contain anything, even something like this:
';DROP TABLE dbAddress--
Think very carefully about what would happen if someone entered something like that in your Address Line 1 field. The only correct solution here is to use the built-in sp_executesql stored procedure. Learn it, use it.
Aside from that, I think at least part of your problem might be that your #SQL variable is only 255 characters. It's easily possible your query is running out of space.