Invalid cast exception? - c#

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
///...

Related

Multiple rows Sql Server update using a Dedicated Table Value parameter - Stored Procedure

Using the below stored procedure I am able to select a variable section of a table, given the Row index of each record. I tried to create another stored procedure similar to the MulTselect, only this time the table value parameter will have another column for the new value for a MulTUpdate stored procedure.
[RowIndex] int, [NewVal] [varchar] (4000) NOT NULL
the question is, given the record - Rowindex and "NewValue", is it possible to do an UPDATE on multiple records like in select procedure below?
--sproc signature
CREATE Proc [dbo].[MulTSELECTViaRowIndexSpTVP]
#SelectedTableName varchar (50),
#SelectedAction varchar(10),
#TestMulTSELECTViaRowIndexTVPar dbo.TestMulTSELECTViaRowIndexTVType READONLY
SET #CmdStr = 'SELECT * FROM ' + #SelectedTableName + '
WHERE RowIndex in (SELECT RowIndex from #TestMulTSELECTViaRowIndexTVPar);'
EXEC sp_executesql #CmdStr,N' #TestMulTSELECTViaRowIndexTVPar dbo.TestMulTSELECTViaRowIndexTVType READONLY',
#TestMulTSELECTViaRowIndexTVPar= #TestMulTSELECTViaRowIndexTVPar
AS I was looking through my old stored procedures i found one that stared me thinking in the right way, so this is what i got to compile, not yet tested.
Declare #TotalRec int = (Select COUNT(RowIndex) from #TestMulTiActMulTColIndexTVPar);
Declare #Iter int =0, #Count int =0;
While #Iter < #TotalRec
Begin
Declare #curRowIndex int=
(
select RowIndex from
(select row_number() over (order by RowIndex) as RowN,
* from #TestMulTiActMulTColIndexTVPar) T where T.RowN =(#Iter+1)
);
Declare #CurVal varchar(4000) = (Select [StrVal] from #TestMulTiActMulTColIndexTVPar WHERE RowIndex=#curRowIndex);
SET #CmdStr = 'UPDATE ' + #SelectedSDTOName + ' SET ' + #SelectedColName + ' = ' + QUOTENAME(#CurVal, '''') + ' WHERE RowIndex = ' + CAST(#curRowIndex as nvarchar);
EXEC sp_executesql #CmdStr,N' #TestMulTiActMulTColIndexTVPar dbo.TestMulTiActMulTColIndexTVType READONLY',
#TestMulTiActMulTColIndexTVPar= #TestMulTiActMulTColIndexTVPar;
Set #Iter = #Iter + 1;
End
SELECT 'EffRows' = #Iter;
this is the best i could compose with my skills,
as it iterates it's executing each update command(within the while loop) separately as opposed to the select procedure
SELECT * FROM ' + #SelectedTableName + '
WHERE RowIndex in (SELECT RowIndex from #TestMulTSELECTViaRowIndexTVPar);'
so i don't know if it will best perform as i coded here...
any comment will be very welcome.
and thanks for your time.

Inserting a value one at a time

I have a table that holds form details, the form num(identity column) and the 5 columns for the Questions Score.
My insert proc for the form is very basic:
ALTER PROC [dbo].[Insert_New_Form]
#questionOne int, #questionTwo int, #questionThree int,
#questionFour int, #questionFive Int as
begin
Insert into Questionire_Form values (
#questionOne, #questionTwo, #questionThree,
#questionFour, #questionFive)
end
and I hold an int call answer that it's value changes between radio button selection (scoring).
My question is, how do I write a procedure to insert all of the answers in one row, meaning at each click on "next" button the score for the specific answer will be inserted to the row at the specific column.
and how do I wirte the update procedure should I use chack again button to go through the form?
I am using MS SQL 2012
I hope the following code will help you
CREATE PROCEDURE add_Score
#userID INT
#questionNumber INT,
#score INT
AS
DECLARE #ColumnaName VARCHAR(100)
DECLARE #sql VARCHAR(1000)
SET #ColumnName =
( CASE #questionNumber
WHEN 1 THEN 'ColumnOne'
WHEN 2 THEN 'ColumnTwo'
WHEN 3 THEN 'ColumnThree'
WHEN 4 THEN 'ColumnFour'
END )
IF EXISTS(SELECT * FROM Questionire_Form WHERE UserID = #userID) THEN
BEGIN
SET #sql = 'UPDATE Questionire_Form SET ' + #ColumnName + ' = ' + #score + ' WHERE UserID = ' + #userID
END
ELSE
BEGIN
SET #sql = 'INSERT INTO Questionire_Form (UserID, ' + #ColumnName + ') VALUES(' + #userID + ', ' + #score + ')'
END
EXEC(#sql)

c# adding a variable in a SQL dynamic pivot string

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.

Getting specific column name of a table

I am working on a project and I got stuck with a query in which I want to get the specific column name of a table whose value is "no."
I have a table with name subscription and it has four fields; id(integer), email(varchar), sms(varchar), phone(varchar) and my email, sms and phone field have values either 'yes' or 'no'.
Now I want to retrieve the name of only those columns which has a value 'no'.
I want to execute this query in mysql.
I have tried the following query which is returning me the complete row wherever there is even one occurence of 'no':
SELECT * FROM test.subscription WHERE 'no' IN (email,sms,phone);
Like i have these two rows now i want to select the column name where value='no' and id=1
How about something cheap and cheerful using a case statement like:
SELECT ID, 'ColName' = CASE
WHEN email = 'no' THEN 'email'
END,
'ColName2' = CASE
WHEN sms = 'no' THEN 'sms'
END,
'ColName3' = CASE
WHEN phone = 'no' THEN 'phone'
END
FROM subscription
where ID = 2
I cant put this as a comment because of less privileges, but if you are looking to search a value which is held by a table (could be any column) - you might check this SO post
Using the code from the same post -
DECLARE #Results TABLE(ColumnName nvarchar(370), ColumnValue nvarchar(3630))
DECLARE #SearchStr nvarchar(100)
DECLARE #TableName nvarchar(256), #ColumnName nvarchar(128), #SearchStr2 nvarchar(110)
SET #TableName = 'no'
SET #SearchStr2 = QUOTENAME('%' + 'no' + '%','''')
SET #ColumnName = ''
SET #TableName = '[test].[dbo].[subscription]'
WHILE (#TableName IS NOT NULL) AND (#ColumnName IS NOT NULL)
BEGIN
SET #ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(#TableName, 2)
AND TABLE_NAME = PARSENAME(#TableName, 1)
AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
AND QUOTENAME(COLUMN_NAME) > #ColumnName
)
IF #ColumnName IS NOT NULL
BEGIN
INSERT INTO #Results
EXEC
(
'SELECT ''' + #TableName + '.' + #ColumnName + ''', LEFT(' + #ColumnName + ', 3630)
FROM ' + #TableName + ' (NOLOCK) ' +
' WHERE ' + #ColumnName + ' LIKE ' + #SearchStr2
)
END
END
SELECT ColumnName, ColumnValue FROM #Results
If i got the Question right, i think the following Query might work
SELECT *
FROM test.subscription
WHERE 1=1
and
(email = 'no'
or
email = 'no'
or
sms = 'no'
)
and id=(your values)

Error converting data type varchar to bigint

I am retrieving values from listbox and formatting them in string as
if (lbRaisedByLogin.SelectedIndex != -1)
{
foreach (ListItem item in lbRaisedByLogin.Items)
{
if (item.Selected == true)
{
sb.AppendFormat("{0},", item.Value);
}
}
searchCase.raisedByLogin = sb.ToString().TrimEnd(Convert.ToChar(","));
sb.Length = 0;
}
I am passing these strings to store procedure as parameter (Datatype-- Varchar(Max))
in stored procedure I am comparing these values like
SELECT * FROM AUS_CID_Cases
WHERE
AddedBy IN ( #raisedByLogin )
Where #raisedByLogin is one of the parameter i passed. It has values like #raisedByLogin="4,2,1"
AddedBy has datatype bigint.
When I run code I get error as "Error converting data type varchar to bigint.".. I understand it is because AddedBy column has datatype bigint. I can not change that datatype.
However when i cast AddedBy like
SELECT * FROM AUS_CID_Cases
WHERE
CAST(AddedBy as VARCHAR) IN ( #raisedByLogin )
I dont get error, but nothing is selected i.e I dont get any result from select statement.
What can I do?
First create this view
CREATE FUNCTION [dbo].[Split](#String varchar(8000), #Delimiter char(1))
returns #temptable TABLE (items varchar(8000))
as
begin
declare #idx int
declare #slice varchar(8000)
select #idx = 1
if len(#String)<1 or #String is null return
while #idx!= 0
begin
set #idx = charindex(#Delimiter,#String)
if #idx!=0
set #slice = left(#String,#idx - 1)
else
set #slice = #String
if(len(#slice)>0)
insert into #temptable(Items) values(#slice)
set #String = right(#String,len(#String) - #idx)
if len(#String) = 0 break
end
return
then change the query to this and try,
SELECT * FROM AUS_CID_Cases
WHERE
CAST(AddedBy as VARCHAR) IN ( select * from split(#raisedByLogin,',') )
found above Function here, and managed to solve this issue sometime back...
try to build SQL select query inside stored procedure and execute after that.
DECLARE #raisedByLogin varchar(600)
SET #SQL =
'SELECT * FROM AUS_CID_Cases
WHERE
AddedBy IN (' + #raisedByLogin + ')'
EXEC(#SQL)
check How to pass a list of values or array to SQL Server stored procedure? for more information

Categories