Error in MySql Query Syntax - c#

I am trying to create a MySql stored procedure through C#. I have created some other as well but when I try to execute the Query via MySqlCommand.ExecuteNonQuery its throws a exception that you query syntax is not compatible. Here is the exception message:
You have an error in your SQL syntax;
check the manual that corresponds to
your MySQL server version for the
right syntax to use near 'SET
VariableRecordExists = (SELECT
COUNT(*) FROM SmartCache_Sync WHERE
MachineNa' at line 10
And here I am trying to build the query string:
string sql = #"CREATE PROCEDURE SmartCache_UpdateSync
(
VariableMachineName varchar(50)
)
BEGIN
DECLARE VariableRecordExists int;
DECLARE VariableSetDate datetime;
START TRANSACTION;
SET VariableSetDate= Now()
SET VariableRecordExists = (SELECT COUNT(*) FROM SmartCache_Sync WHERE MachineName = VariableMachineName)
IF VariableRecordExists = 1
THEN
UPDATE SmartCache_Sync
SET LastUpdate = VariableSetDate
WHERE MachineName= VariableMachineName;
ELSE
INSERT INTO SmartCache_Sync
(MachineName,LastUpdate)
VALUES (VariableMachineName,VariableSetDate);
END IF;
COMMIT;
SELECT VariableSetDate;
END";
I don't know where I am making a mistake. Probably I am missing a semi colon ; somewhere or what. I would be obliged if anyone could help me.

I don't know about making queryies in c#, but normally the ; is the end of your query: so if you don't change the delimiter, you are ending your command early. normally you would do something like this:
delimiter //
CREATE PROCEDURE simpleproc (OUT param1 INT)
BEGIN
SELECT COUNT(*) INTO param1 FROM t;
END//
delimiter ;
from:
http://dev.mysql.com/doc/refman/5.0/en/create-procedure.html

Slightly off-topic - but...
In general, prefer "if exists (select...)" to "select count(*)..." when all you want to do is check if any rows exist. It is far cheaper than actually counting all the rows.
And secondly, it looks as though you are trying to do an "upsert", which in MySQL would be
INSERT INTO SmartCache_Sync(MachineName,LastUpdate)
VALUES (VariableMachineName,VariableSetDate)
ON DUPLICATE KEY UPDATE LastUpdate = VariableSetDate
and then you don't need the explicit transaction either.
This of course assumes that MachineName is a primary key, which I'm guessing it is.

My guess was right I was missing a ";". And honestly speaking it took me 2 hours to that out.
**
SET VariableSetDate= Now();
SET VariableRecordExists = (SELECT COUNT(*) FROM SmartCache_Sync
WHERE MachineName =
VariableMachineName);
**
Both the statements didn't have ";" at the end

CREATE PROCEDURE SmartCache_UpdateSync
(
VariableMachineName varchar(50)
)
BEGIN
DECLARE VariableRecordExists int;
DECLARE VariableSetDate datetime;
START TRANSACTION;
SET VariableSetDate= Now()
(SELECT VariableRecordExists = COUNT(*) FROM SmartCache_Sync WHERE MachineName = VariableMachineName)
IF VariableRecordExists = 1
THEN
UPDATE SmartCache_Sync
SET LastUpdate = VariableSetDate
WHERE MachineName= VariableMachineName;
ELSE
INSERT INTO SmartCache_Sync
(MachineName,LastUpdate)
VALUES (VariableMachineName,VariableSetDate);
END IF;
COMMIT;
SELECT VariableSetDate;
END";

Related

Complex types show no result for a stored procedure

I have a stored procedure I would like to use its result in a Web API (C#).
I must miss something since I'm getting no result nor in Complex Types (in EF model) neither in Functions Imports (I can see the stored procedure in Functions Imports but it does not return any value, as expected).
This is my stored procedure (I have erased some non-important data in order to make it shorter)
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
#main_id BIGINT,
#id_ze_mish BIGINT,
#id_nof BIGINT,
#loggedInUser VARCHAR(20)
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
BEGIN TRANSACTION [TransactionUniteSingles]
OPEN SYMMETRIC KEY io_key DECRYPTION BY CERTIFICATE chn_cert
-- Step 1
UPDATE [dbo].[t1]
SET deleted = 1,
WHERE id_nof = #id_nof
AND id_ze = #id_ze_mish
-- Step 2
UPDATE [dbo].[t_no_nir]
SET update_stamp = GETDATE(),
[user_name] = #loggedInUser
WHERE id_nof = #id_nof
AND ms_zehut_mazmin = #id_ze_mish
-- Step 3
CREATE TABLE #mainPrice
(
id INT,
fName VARCHAR(20),
lName VARCHAR(20)
)
INSERT INTO #mainPrice
EXEC [dbo].[io_sp_get_some_data_foo] #id
IF(EXISTS(select * from #mainPrice))
BEGIN
DECLARE #totalAmount INT;
SELECT #totalAmount = (main_price + price_tip + price_visa)
FROM #mainPrice
DROP TABLE #mainPrice
UPDATE [dbo].[t_4]
SET amount = #totalAmount,
update_stamp = GETDATE(),
[user_name] = #loggedInUser
WHERE id_nof = #id_nof
AND id = #main_id
CLOSE ALL SYMMETRIC KEYS
COMMIT TRANSACTION [TransactionUniteSingles]
SELECT CAST(1 as BIT) as 'Status', 'Succeeded' as 'ReturnMessage'
END
ELSE
BEGIN
SELECT CAST(0 as BIT) as 'Status', 'ADMIN - Unite Singles as 'ReturnMessage'
END
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION [TransactionUniteSingles]
SELECT CAST(0 as BIT) as 'Status', 'ADMIN - Unite Singles' as 'ReturnMessage'
END CATCH
END
Please note - when running the stored procedure as standalone, it works perfectly and return what expected.
Check what happens when you call your procedure with NULL input parameters. If the result is not a table then EF will not generate the complex result.
Try following:
-- declare table at SP begin
DECLARE #ResultTable TABLE(
Status BIT NOT NULL,
ResultMessage NVARCHAR(50) NOT NULL
)
-- insert data where you need
INSERT INTO #ResultTable
(
Status,
ResultMessage
)
VALUES
( NULL, -- Status - bit
N'' -- ResultMessage - nvarchar(50)
)
-- at SP end select result from table
SELECT * FROM #ResultTable
I found out that my problem is with my temp table.
when using SET FMTONLY OFF at the top of my SP or above the temp table(#mainPrice in my case) then everything works like a charm and suddenly the Complex Types shows my SP.
Another solution is using a variable table: DECLARE TABLE #mainPrice.
Both do the work.
I'll be happy to know why it happens and why C# refused to get a temp table as part of my SP , but at the moment I found the solution needed.

How to check if FileTable is enabled in SQL Server database [duplicate]

I would like this to be the ultimate discussion on how to check if a table exists in SQL Server 2000/2005 using SQL Statements.
Here are two possible ways of doing it. Which one is the standard/best way of doing it?
First way:
IF EXISTS (SELECT 1
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE='BASE TABLE'
AND TABLE_NAME='mytablename')
SELECT 1 AS res ELSE SELECT 0 AS res;
Second way:
IF OBJECT_ID (N'mytablename', N'U') IS NOT NULL
SELECT 1 AS res ELSE SELECT 0 AS res;
MySQL provides the simple
SHOW TABLES LIKE '%tablename%';
statement. I am looking for something similar.
For queries like this it is always best to use an INFORMATION_SCHEMA view. These views are (mostly) standard across many different databases and rarely change from version to version.
To check if a table exists use:
IF (EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'TheSchema'
AND TABLE_NAME = 'TheTable'))
BEGIN
--Do Stuff
END
Also note that if for any reason you need to check for a temporary table you can do this:
if OBJECT_ID('tempdb..#test') is not null
--- temp table exists
We always use the OBJECT_ID style for as long as I remember
IF OBJECT_ID('*objectName*', 'U') IS NOT NULL
Please see the below approaches,
Approach 1: Using INFORMATION_SCHEMA.TABLES view
We can write a query like below to check if a Customers Table exists in the current database.
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'Customers')
BEGIN
PRINT 'Table Exists'
END
Approach 2: Using OBJECT_ID() function
We can use OBJECT_ID() function like below to check if a Customers Table exists in the current database.
IF OBJECT_ID(N'dbo.Customers', N'U') IS NOT NULL
BEGIN
PRINT 'Table Exists'
END
Approach 3: Using sys.Objects Catalog View
We can use the Sys.Objects catalog view to check the existence of the Table as shown below:
IF EXISTS(SELECT 1 FROM sys.Objects WHERE Object_id = OBJECT_ID(N'dbo.Customers') AND Type = N'U')
BEGIN
PRINT 'Table Exists'
END
Approach 4: Using sys.Tables Catalog View
We can use the Sys.Tables catalog view to check the existence of the Table as shown below:
IF EXISTS(SELECT 1 FROM sys.Tables WHERE Name = N'Customers' AND Type = N'U')
BEGIN
PRINT 'Table Exists'
END
Approach 5: Avoid Using sys.sysobjects System table
We should avoid using sys.sysobjects System Table directly, direct access to it will be deprecated in some future versions of the Sql Server. As per Microsoft BOL link, Microsoft is suggesting to use the catalog views sys.objects/sys.tables instead of sys.sysobjects system table directly.
IF EXISTS(SELECT name FROM sys.sysobjects WHERE Name = N'Customers' AND xtype = N'U')
BEGIN
PRINT 'Table Exists'
END
referred from: http://sqlhints.com/2014/04/13/how-to-check-if-a-table-exists-in-sql-server/
Looking for a table on a different database:
if exists (select * from MyOtherDatabase.sys.tables where name = 'MyTable')
print 'Exists'
Just wanted to mention one situation where it would probably be a little easier to use the OBJECT_ID method. The INFORMATION_SCHEMA views are objects under each database-
The information schema views are defined in a special schema named
INFORMATION_SCHEMA. This schema is contained in each database.
https://msdn.microsoft.com/en-us/library/ms186778.aspx
Therefore all tables you access using
IF EXISTS (SELECT 1
FROM [database].INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE='BASE TABLE'
AND TABLE_NAME='mytablename')
SELECT 1 AS res ELSE SELECT 0 AS res;
will only reflect what is in [database]. If you wanted to check if tables in another database exist, without dynamically changing the [database] each time, OBJECT_ID will let you do this out of the box. Ex-
IF OBJECT_ID (N'db1.schema.table1', N'U') IS NOT NULL
SELECT 1 AS res ELSE SELECT 0 AS res;
works just as well as
IF OBJECT_ID (N'db2.schema.table1', N'U') IS NOT NULL
SELECT 1 AS res ELSE SELECT 0 AS res;
SQL SERVER 2016 Edit:
Starting with 2016, Microsoft simplified the ability to check for non-existent objects prior to dropping, by adding the if exists keywords to drop statements. For example,
drop table if exists mytablename
will do the same thing as OBJECT_ID / INFORMATION_SCHEMA wrappers, in 1 line of code.
https://blogs.msdn.microsoft.com/sqlserverstorageengine/2015/11/03/drop-if-exists-new-thing-in-sql-server-2016/
IF OBJECT_ID('mytablename') IS NOT NULL
Using the Information Schema is the SQL Standard way to do it, so it should be used by all databases that support it. See Approach 1 in this answer.
You can use below code
IF (OBJECT_ID('TableName') IS NOT NULL )
BEGIN
PRINT 'Table Exists'
END
ELSE
BEGIN
PRINT 'Table NOT Exists'
END
Or
IF (EXISTS (SELECT * FROM sys.tables WHERE [name] = 'TableName'))
BEGIN
PRINT 'Table Exists'
END
ELSE
BEGIN
PRINT 'Table NOT Exists'
END
IF EXISTS
(
SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[Mapping_APCToFANavigator]')
AND
type in (N'U')
)
BEGIN
-- Do whatever you need to here.
END
Here in the above code, the table name is Mapping_APCToFANavigator.
If you need to work on different databases:
DECLARE #Catalog VARCHAR(255)
SET #Catalog = 'MyDatabase'
DECLARE #Schema VARCHAR(255)
SET #Schema = 'dbo'
DECLARE #Table VARCHAR(255)
SET #Table = 'MyTable'
IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_CATALOG = #Catalog
AND TABLE_SCHEMA = #Schema
AND TABLE_NAME = #Table))
BEGIN
--do stuff
END
I know it is an old question but I have found this possibility if you plan to call it often.
create procedure Table_Exists
#tbl varchar(50)
as
return (select count(*) from sysobjects where type = 'U' and name = #tbl)
go
Just adding here, for the benefit of developers and fellow DBAs
a script that receives #Tablename as a parameter
(which may or may not contain the schemaname) and returns the info below if the schema.table exists:
the_name object_id the_schema the_table the_type
[Facts].[FactBackOrder] 758293761 Facts FactBackOrder Table
I produced this script to be used inside other scripts every time I need to test whether or not a table or view exists, and when it does, get its object_id to be used for other purposes.
It raises an error when either you passed an empty string, wrong schema name or wrong table name.
this could be inside a procedure and return -1 for example.
As an example, I have a table called "Facts.FactBackOrder" in one of my Data Warehouse databases.
This is how I achieved this:
PRINT 'THE SERVER IS ' + ##SERVERNAME
--select db_name()
PRINT 'THE DATABASE IS ' + db_NAME()
PRINT ''
GO
SET NOCOUNT ON
GO
--===================================================================================
-- #TableName is the parameter
-- the object we want to deal with (it might be an indexed view or a table)
-- the schema might or might not be specified
-- when not specified it is DBO
--===================================================================================
DECLARE #TableName SYSNAME
SELECT #TableName = 'Facts.FactBackOrder'
--===================================================================================
--===================================================================================
DECLARE #Schema SYSNAME
DECLARE #I INT
DECLARE #Z INT
SELECT #TableName = LTRIM(RTRIM(#TableName))
SELECT #Z = LEN(#TableName)
IF (#Z = 0) BEGIN
RAISERROR('Invalid #Tablename passed.',16,1)
END
SELECT #I = CHARINDEX('.',#TableName )
--SELECT #TableName ,#I
IF #I > 0 BEGIN
--===================================================================================
-- a schema and table name have been passed
-- example Facts.FactBackOrder
-- #Schema = Fact
-- #TableName = FactBackOrder
--===================================================================================
SELECT #Schema = SUBSTRING(#TABLENAME,1,#I-1)
SELECT #TableName = SUBSTRING(#TABLENAME,#I+1,#Z-#I)
END
ELSE BEGIN
--===================================================================================
-- just a table name have been passed
-- so the schema will be dbo
-- example Orders
-- #Schema = dbo
-- #TableName = Orders
--===================================================================================
SELECT #Schema = 'DBO'
END
--===================================================================================
-- Check whether the #SchemaName is valid in the current database
--===================================================================================
IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.SCHEMATA K WHERE K.[SCHEMA_NAME] = #Schema ) BEGIN
RAISERROR('Invalid Schema Name.',16,1)
END
--SELECT #Schema as [#Schema]
-- ,#TableName as [#TableName]
DECLARE #R1 TABLE (
THE_NAME SYSNAME
,THE_SCHEMA SYSNAME
,THE_TABLE SYSNAME
,OBJECT_ID INT
,THE_TYPE SYSNAME
,PRIMARY KEY CLUSTERED (THE_SCHEMA,THE_NAME)
)
;WITH RADHE_01 AS (
SELECT QUOTENAME(SCHEMA_NAME(O.schema_id)) + '.' + QUOTENAME(O.NAME) AS [the_name]
,the_schema=SCHEMA_NAME(O.schema_id)
,the_table=O.NAME
,object_id =o.object_id
,[the_type]= CASE WHEN O.TYPE = 'U' THEN 'Table' ELSE 'View' END
from sys.objects O
where O.is_ms_shipped = 0
AND O.TYPE IN ('U','V')
)
INSERT INTO #R1 (
THE_NAME
,THE_SCHEMA
,THE_TABLE
,OBJECT_ID
,THE_TYPE
)
SELECT the_name
,the_schema
,the_table
,object_id
,the_type
FROM RADHE_01
WHERE the_schema = #Schema
AND the_table = #TableName
IF (##ROWCOUNT = 0) BEGIN
RAISERROR('Invalid Table Name.',16,1)
END
ELSE BEGIN
SELECT THE_NAME
,THE_SCHEMA
,THE_TABLE
,OBJECT_ID
,THE_TYPE
FROM #R1
END
In SQL Server 2000 you can try:
IF EXISTS(SELECT 1 FROM sysobjects WHERE type = 'U' and name = 'MYTABLENAME')
BEGIN
SELECT 1 AS 'res'
END
IF EXISTS
(
SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'PutSchemaHere'
AND
TABLE_NAME = 'PutTableNameHere'
)
Something important to know for anybody who hasn't found their solution yet:
SQL server != MYSQL.
If you want to do it with MYSQL, it is quite simple
$sql = "SELECT 1 FROM `db_name`.`table_name` LIMIT 1;";
$result = mysql_query($sql);
if( $result == false )
echo "table DOES NOT EXIST";
else
echo "table exists";
Posting this here because it's the top hit at Google.
I've had some problems either with selecting from INFORMATIONAL_SCHEME and OBJECT_ID. I don't know if it's an issue of ODBC driver or something.. Queries from SQL management studio, both, were okay.
Here is the solution:
SELECT COUNT(*) FROM <yourTableNameHere>
So, if the query fails, there is, probably, no such table in the database (or you don't have access permissions to it).
The check is done by comparing the value (integer in my case) returned by SQL executor which deals with ODBC driver..
if (sqlexec(conectionHandle, 'SELECT COUNT(*) FROM myTable') == -1) {
// myTable doesn't exist..
}
IF EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE
TABLE_CATALOG = 'Database Name' and
TABLE_NAME = 'Table Name' and
TABLE_SCHEMA = 'Schema Name') -- Database and Schema name in where statement can be deleted
BEGIN
--TABLE EXISTS
END
ELSE BEGIN
--TABLE DOES NOT EXISTS
END
You can use this :
IF OBJECT_ID (N'dbo.T', N'U') IS NOT NULL
BEGIN
print 'deleted table';
drop table t
END
else
begin
print 'table not found'
end
Create table t (id int identity(1,1) not null, name varchar(30) not null, lastname varchar(25) null)
insert into t( name, lastname) values('john','doe');
insert into t( name, lastname) values('rose',NULL);
Select * from t
1 john doe
2 rose NULL
-- clean
drop table t
I think the following query works:
IF EXISTS (select * from sys.tables
WHERE name='mytablename' )
BEGIN
print 'table exists in the database'
END
IF EXISTS ( SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.TableName') AND OBJECTPROPERTY(id, N'IsUserTable') = 1 )
BEGIN
SELECT * FROM dbo.TableName;
END
GO
There is one more option to check if the table exists across databases
IF EXISTS(SELECT 1 FROM [change-to-your-database].SYS.TABLES WHERE NAME = 'change-to-your-table-name')
BEGIN
-- do whatever you want
END
If anyone is trying to do this same thing in linq to sql (or especially linqpad) turn on option to include system tables and views and do this code:
let oSchema = sys.Schemas.FirstOrDefault(s=>s.Name==a.schema )
where oSchema !=null
let o=oSchema!=null?sys.Objects.FirstOrDefault (o => o.Name==a.item && o.Schema_id==oSchema.Schema_id):null
where o!=null
given that you have an object with the name in a property called item, and the schema in a property called schema where the source variable name is a
select name from SysObjects where xType='U' and name like '%xxx%' order by name
If this is to be the 'ultimate' discussion, then it should be noted that Larry Leonard's script can query a remote server as well if the servers are linked.
if exists (select * from REMOTE_SERVER.MyOtherDatabase.sys.tables where name = 'MyTable')
print 'Exists'
-- -- create procedure to check if a table exists
DELIMITER $$
DROP PROCEDURE IF EXISTS `checkIfTableExists`;
CREATE PROCEDURE checkIfTableExists(
IN databaseName CHAR(255),
IN tableName CHAR(255),
OUT boolExistsOrNot CHAR(40)
)
BEGIN
SELECT count(*) INTO boolExistsOrNot FROM information_schema.TABLES
WHERE (TABLE_SCHEMA = databaseName)
AND (TABLE_NAME = tableName);
END $$
DELIMITER ;
-- -- how to use : check if table migrations exists
CALL checkIfTableExists('muDbName', 'migrations', #output);
i taking here creating a view as example.
Because ALTER/CREATE commands can't be within BEGIN/END blocks. You need to test for existence and the drop it before doing a create
IF Object_ID('TestView') IS NOT NULL
DROP VIEW TestView
GO
CREATE VIEW TestView
as
. . .
GO
If you are woried about the permissions being lost you can script the GRANT statements as well and re-run those at the end.
You could wrap the create/alter into a string and do an EXEC - that might get ugly for large views
DECLARE #SQL as varchar(4000)
-- set to body of view
SET #SQL = 'SELECT X, Y, Z FROM TABLE'
IF Object_ID('TestView') IS NULL
SET #SQL = 'CREATE VIEW TestView AS ' + #SQL
ELSE
SET #SQL = 'ALTER VIEW TestView AS ' + #SQL
Run this query to check if the table exists in the database:
IF(SELECT TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'YourTableName') IS NOT NULL
PRINT 'Table Exists';
consider in one database you have a table t1. you want to run script on other Database like - if t1 exist then do nothing else create t1.
To do this open visual studio and do the following:
Right click on t1, then Script table as, then DROP and Create To, then New Query Editor
you will find your desired query. But before executing that script don't forget to comment out the drop statement in the query as you don't want to create new one if there is already one.
Thanks

How to find parameters in sql query using C# Ado.Net

I have got this query which is entered by user at run time.
SELECT * FROM Reports
WHERE ReportDate > DATEADD(d, #Days, getdate())
AND ReportCode = cast(#Reportcode as int)
Is there any way in C# .Net or SQL to retrieve the parameter names #Days and #ReportCode from this sql query?
Regex or string matching using # character is not full proof as parameter names may or may not end with a space. They can be immediately followed by a comma or parenthesis etc. and the name itself can contain a special character.
If I execute this query without providing parameter values, the sql engine throws exception Must declare the scalar variable "#Days". I can catch the exception and get first parameter name, but then it would be very complex to get next parameter in query.
exec sp_describe_undeclared_parameters N'SELECT * FROM Reports
WHERE ReportDate > DATEADD(d, #Days, getdate())
AND ReportCode = cast(#Reportcode as int)'
outputs:
parameter_ordinal name suggested_system_type_id suggested_system_type_name
----------------- ------------- ------------------------ ----------------------------
1 #Days 56 int
2 #Reportcode 56 int
(lots more columns skipped)
However, this is a SQL Server feature, not an ADO.NET one.
If I execute this query without providing parameter values,
The key trick here is remarkably simple: supply the correct parameters
Note: you can also use #params to tell it about the ones you already know about. For more details, see the documentation.
create table login_db(UserName varchar(50),Password varchar(50))
go
create proc sp_logininsertdb
(#UserName varchar(50),#Password varchar(50))
as
begin
insert into login_db values(#UserName,#Password)
end
drop proc sp_logininsertdb
exec sp_logininsertdb #UserName='admin',#Password='admin'
go
create proc sp_loginviewdb
as
select *from login_db
exec sp_loginview_db
create table addemployee_db(id int identity(1,1),employeename varchar(50),dob Date,location varchar(50),gender varchar(50),doj Date,experience int,ctc int,designation varchar(50),unithead varchar(50),projectid int)
go
create procedure sp_addemployeedb(#id int out,#employeename varchar(50),#dob Date,#location varchar(50),#gender varchar(50),#doj Date,#experience int,#ctc int,#designation varchar(50),#unithead varchar(50),#projectid int)
as
begin
insert into addemployee_db values (#employeename,#dob,#location,#gender,#doj,#experience,#ctc,#designation,#unithead,#projectid)
set #id=##IDENTITY
end
declare #result int
exec sp_addemployee #id=#result output,#employeename='lokesh',
#dob='03/16/1994',#location='tvm',#gender='male',#doj='01/18/2016',
#experience=1,#ctc=4,#designation='ASE',#unithead='head1',#projectid='001'
print #result
go
create proc sp_viewemployee_db
as
begin
select * from addemployee_db
end
exec sp_viewemployee_db
drop proc sp_updateemployee_db
drop proc sp_editemployee_db
go
create procedure sp_editemployee_db(#id int,#employeename varchar(50),#dob Date,#location varchar(50),#gender varchar(50),#doj Date,#experience int,#ctc int,#designation varchar(50),#unithead varchar(50),#projectid int)
as
begin
update addemployee_db set employeename=#employeename,dob=#dob,location=#location,gender=#gender,doj=#doj,experience=#experience,ctc=#ctc,designation=#designation,unithead=#unithead,projectid=#projectid
where id=#id
end
exec sp_editemployee_db #id=10,#employeename='avaneesh',
#dob='10/11/1992',#location='Trivandrum',#gender='male',#doj='01/18/2016',
#experience=2,#ctc=7,#designation='ASET',#unithead='head2',#projectid='002'
go
create proc sp_updateemployee_db
as
begin
select * from addemployee_db
exec sp_updateemployee_db
end
drop proc sp_deletemployee_db
go
create proc sp_deletemployee_db
(#id int out)
as
begin
delete from addemployee_db where id=#id
end
exec sp_deletemployee #id=12
go
create proc sp_deleteemployee_db
as
begin
select * from addemployee_db
exec sp_deleteemployee_db
end
exec sp1_login_db
create table databinding_db(location varchar(20))
go
create proc sp_databindinginsertdb
(
#location varchar(20)
)
as
begin
insert into databinding_db
values(#location)
end
drop table databinding_db
drop proc sp_databindinginsertdb
select * from databinding_db
exec sp_databindinginsertdb 'chennai'
exec sp_databindinginsertdb 'trivandrum'
exec sp_databindinginsertdb 'puducherry'
exec sp_databindinginsertdb 'trichy'
select * from databinding_db
go
create proc sp_databindingdb
as
begin
select * from databinding_db
end

must declare the scalar variable '#custid' using dbcontext.Database.SqlQuery?

I am trying to execute stored procedure from bcontext.Database.SqlQuery using EF5.
It is throwing an error must declare the scalar variable '#custid'
var results = _MiscContext.Database.SqlQuery<int>(
"exec sp_GetStaff #custid",
customerNumber).ToList<int>();
SP returns 1 if customerNumber is staff otherwise it return empty row.
ALTER PROCEDURE [dbo].[sp_GetStaff]
#custid varchar(12)
AS
BEGIN
SET NOCOUNT ON;
SELECT
1 AS [C1]
FROM [dbo].[Staff] with (nolock)
WHERE [CUSTOMER_ID] = #custid
END
How to manage this?
Since you're using named parameters, you have to specify the matching name for the parameter you're passing.
var results = _MiscContext.Database.SqlQuery<int>(
"exec sp_GetStaff #custid",
new SqlParameter("custid", customerNumber)).ToList<int>();
Try
var results = _MiscContext.Database.SqlQuery<int>(
"exec sp_GetStaff {0}",
customerNumber).ToList();

Passing C# parameters to a stored procedure report

I am trying to trigger a report to run with "select all" checked for a field FiscalYearId, which is a string type. I can successfully pass one string such as "2" and the report will find it. However, when I try to pass "select all" or "2,3,4", the multi-check field does not pick up on this.
Here is part of the stored procedure from the report:
ALTER PROCEDURE [dbo].[...]
#FiscalYearId varchar (100) = null ,
...
select ...
where ...
and (#FiscalYearID IS NULL OR p.FiscalYearId IN (SELECT * FROM SPLIT(#FiscalYearID, ',')))
my c# code which triggers the report to pop up in a radwindow is:
`string years = "2,3,4";
newWindow.NavigateUrl = "../Reporting/SingleReport.aspx?Report=AdHocSourcingReport&VendorID="
+ vendorId + "&VendorReport=true" + "&FiscalYearId="+years;`
Currently, the vendorId string and VendorReport boolean pull through successfully, it is the string separated by commas that is not populating when the report is run. I initially tried to send a "select all", which is what I want.. Any help is greatly appreciated!!
This is how I've handled splitting comma delimited strings in the past:
CREATE FUNCTION
[dbo].[GetItemTable]
(
#Items VARCHAR(1000)
)
RETURNS
#ItemTable TABLE
(
RowID INT IDENTITY(1,1) PRIMARY KEY,
item VARCHAR(30)
)
AS
BEGIN
DECLARE #ProcessItems VARCHAR(1000)
DECLARE #CurrentItem VARCHAR(30)
SET #ProcessItems = REPLACE(#Items, '''', '')
IF SUBSTRING(#ProcessItems, LEN(#ProcessItems), 1) ','
SET #ProcessItems = #ProcessItems + ','
WHILE CHARINDEX(',', #ProcessItems) > 0
BEGIN
SET #CurrentItem = LTRIM(CAST(SUBSTRING(#ProcessItems, 0, CHARINDEX(',', #ProcessItems)) AS VARCHAR(30)))
INSERT INTO
#ItemTable
(
item
)
VALUES
(
#CurrentItem
)
SET #ProcessItems = SUBSTRING(#ProcessItems, CHARINDEX(',', #ProcessItems) + 1, LEN(#ProcessItems))
END -- While Schedule
RETURN
END
Obviously, you can change the current item size to whatever you happen to need it to be.
Then just use it like this:
WHERE (p.FiscalYearId IN(SELECT item FROM dbo.GetItemTable(#FiscalYearID)))
I remember doing something similar couple years ago and having same kinds of problem with the list.
Can you try this...
ALTER PROCEDURE [dbo].[...] #FiscalYearId varchar (100) = null ,
... select... where... and
(#FiscalYearID IS NULL OR p.FiscalYearId IN (#FiscalYearID))
Also, if you are sending "Select all" string, you might need to have a condition in your procedure to check that and change the query to "Select id from fiscalyeartable"

Categories