c# adding a variable in a SQL dynamic pivot string - c#

I am trying to show the results of a dynamic pivot in a c# datagridview. So far I have got the following code but I am stumped as how to incorporate the #Date variable in the #query string. What am I missing here? The code works fine with hard coded dates and as it is returns Additional information: Incorrect syntax near '#Date'. Please help,
Thanks,
A
da2.SelectCommand = new SqlCommand(#"DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX);
SET #cols = STUFF((SELECT distinct ',' + QUOTENAME(currency)
FROM Alpha.dbo.Beta
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET #query = 'SELECT Customer, ' + #cols + ' FROM
(
SELECT
Customer, Amount, Currency
FROM Alpha.dbo.Beta
WHERE Date Between ''2010-01-01'' and '#Date' ----PROBLEM AREA----
) x
PIVOT
(
SUM(Amount)
for Currency in (' + #cols + ')
) AS pvt
ORDER BY Customer; '
execute(#query)", MyConnection);
da2.SelectCommand.Parameters.Add("Date", SqlDbType.DateTime).Value = dateTimePicker4.Text;
ds2.Clear();
da2.Fill(ds2);

Correct your code as:
da2.SelectCommand.Parameters.Add("#Date", SqlDbType.DateTime);
da2.SelectCommand.Parameters["#Date"].Value = dateTimePicker4.Text;
Also, use stored procedure instead the query.

Related

SQL Server query showing error when applying search between condition [duplicate]

This question already has answers here:
How to use sp_executesql to avoid SQL Injection
(2 answers)
Closed 5 years ago.
My table data is like this:
enter image description here
I'm using this query:
DECLARE #cols AS NVARCHAR(MAX), #query AS NVARCHAR(MAX)
SELECT #cols = STUFF((SELECT distinct ','+ QUOTENAME('COMPLETE_' + cast(row_number() over(partition by CID order by CID) as varchar(10)))
FROM allleads
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
SET #query = 'SELECT CustomerName, address, CID, ' + #cols +
' FROM (SELECT CustomerName, address, CID, COMPLETE,''COMPLETE_''+ CAST(row_number() over (partition by CID order by RecordDate) as varchar(10)) val from allleads) x PIVOT (MAX(COMPLETE) for val in (' + #cols + ')) p ' execute(#query)
is working fine.
But when I add a search condition between date like this:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX),
#dt AS VARCHAR(10),
#dt1 AS VARCHAR(10) set
#dt='2017/05/18' set
#dt1='2017/07/10'
select #cols = STUFF((SELECT distinct ','+
QUOTENAME('COMPLETE_' +
cast(row_number()
over(partition by CID order by CID) as varchar(10)))
from allleads FOR XML PATH(''),
TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
set #query = 'SELECT CustomerName,address,CID, ' +
#cols + ' from (select CustomerName,address,CID, COMPLETE,''COMPLETE_''+
cast(row_number()
over(partition by CID order by RecordDate) as varchar(10))
val from allleads **where convert(varchar(10),RecordDate,111) between '+#dt+' and '+#dt1+'**) x pivot(max(COMPLETE) for val in (' + #cols + ')) p ' execute(#query)
then it is showing an error:
Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the varchar value '2017/05/19' to data type int.
Please help.
Thanks in advance.
You should really use parameters for constants in a query . . . and use sp_executesql to pass them in.
In your case, the problem is missing quotes around the dates. Instead of:
between '+#dt+' and '+#dt1+'
You can do:
between '''+#dt+''' and '''+#dt1+'''
In other words, the error is occurring when you execute the code, not when you are defining the strings.
You should also learn to write your code in a less sloppy manner. I don't see how even you can read it, much less anyone else.

How to pass in sql "like" condition from c# with single quotes

I have string variable in c#
String Condition = " And LoginName like ''%"+txtLoginName.text+"%''";
I pass this condition variable to a stored procedure like this:
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "GetAllUserMasterBySearch";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Condition ", Condition );
And my stored procedure is here:
create PROCEDURE [dbo].[GetAllUserMasterBySearch] (
#Condition nvarchar(max)
)
as
declare #Query nvarchar(max)
set #Query = 'SELECT
[UserMasterId], [LoginName], [UserName],
[UserType], [MobileNo], [Email],
[IsLogin], [IpAddress]
FROM
UserMaster
WHERE
IsActive = 1 ' + #Condition
print #query
EXEC sp_executesql #Query
How to pass "like" condition from C# ?
You can pass only variable and rewrite your SP as following
alter PROCEDURE [dbo].[GetAllUserMasterBySearch] (
#var nvarchar(max)
) as
declare #Query nvarchar(max)
set #Query = 'SELECT
[UserMasterId]
,[LoginName]
,[UserName]
,[UserType]
,[MobileNo]
,[Email]
,[IsLogin]
,[IpAddress]
FROM
UserMaster
WHERE
IsActive=1 AND LoginName LIKE %' + #var + '%';
print #query
EXEC sp_executesql #Query
Update: If you want to play with dynamic SQL then try ''' instead of ''. Honestly I haven't deal with dynamic SQL for a while since it it terrible and not secure approach (as it was already mentioned in comments)

I want to convert columns to rows based on the condition

My sql query returns the below output.
In C#.Net i have to convert it like below based on RowSequence and ColumnSequence column values.
How to do it.
you have to use dynamic pivot as your row value that needs to pivoted is not fixed:
DECLARE #columns AS NVARCHAR(MAX), #query AS NVARCHAR(MAX)
select #columns = STUFF((SELECT ', ' + QUOTENAME(ColumnName)
from YOURTABLE
group by ColumnName, ColumnSequesnce
order by ColumnSequesnce
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = N'SELECT ' + #columns + N' from
(
select RowSequence, ColumnValue, ColumnName
from YOURTABLE
) x
pivot
(
max(ColumnValue)
for ColumnName in (' + #columns + N')
) p '
exec sp_executesql #query;
You can go for Pivot in Sql
http://blog.sqlauthority.com/2008/06/07/sql-server-pivot-and-unpivot-table-examples/
Try it.

Pass Column Name as parameter

I want to PassColumn name as a paremeter in My SP
And if my tat column exists in first table (Batch_Master), want to fatch value from that column,
And if that column exists in my second table (GTIN_Master), want to fetch value from tat table column,
Each table have columns like..
Batch_Master (Batch_M_id, GTIN(primary key),....etc
GTIN_Master (GTIN (foreign key),..etc)
I have Batch_M_id, and column name as a parameter..
Note: column Name having random datatype, some time int or some time datetime etc
I Try followin SP
CREATE PROCEDURE dbo.StoredProcedure2
#columnName varchar(50),
#batchmId int
AS
if exists(select * from sys.columns
where Name = N'columnName' and Object_ID = Object_ID(NBatch_Master'))
begin
select #columnName from Batch_Master
end
else
begin
select #columnName
from GTIN_Master inner join Batch_Master
on GTIN_Master.GTIN = Batch_Master.GTIN
where Batch_M_id =#batchmId
end
RETURN
What you need when you do not know exactly the query structure you are going to execute, then you have to create a dynamic query, which is actually a form of templating queries.
CREATE PROCEDURE dbo.StoredProcedure2
#columnName varchar(50),
#batchmId int
AS
DECLARE #SQL1 AS VARCHAR(MAX)
DECLARE #SQL2 AS VARCHAR(MAX)
SET #SQL1 = 'select ' + #columnName + ' from Batch_Master'
SET #SQL1 = 'select ' + #columnName + '
from GTIN_Master inner join Batch_Master
on GTIN_Master.GTIN = Batch_Master.GTIN
where Batch_M_id =' + CONVERT(VARCHAR,#batchmId)
IF EXISTS(SELECT * FROM sys.columns WHERE Name = #columnName and Object_ID = Object_ID(N'Batch_Master'))
BEGIN
EXEC (#SQL1)
END
ELSE
BEGIN
EXEC (#SQL2)
END
The above will do what you want but is prone to errors. For instance what if the column passed in the parameter does not exist in the tables used in the second query? You should probably need to check for existence in the second case too.
DECLARE #SQL VARCHAR(MAX)
SET #SQL = 'select ' + #columnName + ' from Batch_Master'
EXECUTE(#SQL)
This SQL:
set nocount on
go
create table One (id int, name varchar(25))
go
create table Two (id int, value varchar(25))
go
insert into One values (1, 'Table One')
insert into Two values (1, 'Table Two')
go
create procedure sp_test_colname
#colname sysname
as
declare #sql nvarchar(2048)
if exists (select 1 from sys.columns where name = #colname and object_id = object_id(N'One'))
set #sql = 'select [' + #colname + '] from [One]'
else
if exists (select 1 from sys.columns where name = #colname and object_id = object_id(N'Two'))
set #sql = 'select [' + #colname + '] from [Two]'
if #sql <> ''
exec sp_executesql #sql
go
exec sp_test_colname 'name'
exec sp_test_colname 'value'
exec sp_test_colname 'somethingelse'
go
drop procedure sp_test_colname
drop table One, Two
Returns the following:
name
-------------------------
Table One
value
-------------------------
Table Two

Invalid cast exception?

I have the following stored procedure:
Create PROCEDURE [dbo].[GETVendorsStatsAgainstSearTerm]
#Date DateTime ,
#SearchId bigint
AS
declare #cmd as varchar(2000)
set #cmd = ' select *, ' + cast(SearchId as varchar) + ' as SearhId from tbl'
exec (#cmd)
I want to treat SearchId as a column to run the select query against. I want to know the correct type for the SearchId column.
I am unable to convert this SearchId column into a long data type in C#. Can anybody help me?
You can try with Convert function
Convert(varchar(50),SearchId )
I guess the problem is that there are some unassigned SearchId's which causes csating a null into varchar.
Try something like this:
//...
set #cmd = CASE
WHEN (SearchId IS NOT NULL) THEN (' select *, ' + cast(SearchId as varchar) + ' as SearhId from tbl')
ELSE ' select *, 0 as SearhId from tbl'
END
///...

Categories