call mysql stored procedure in c# - c#

This is my stored procedure:
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(goals = ''',
goals,
''', round(value, 2), NULL)) AS ',
goals
)
) INTO #sql
FROM sgwebdb.dim_module;
SET #sql = CONCAT('SELECT alternative, ', #sql, ' FROM sgwebdb.dim_module GROUP BY
alternative');
prepare stmt from #sql;
execute stmt;
I need to call this procedure in below code instead of below MySQL query (query1)
C# code -->
protected void Page_Load(object sender, EventArgs e)
{
BindGrid();
}
private void BindGrid()
{
string query1 = "SELECT alternative as 'Alternative',max( case when goals='G1' then round( value, 2 ) end ) as 'Goal 1',max( case when goals='G2' then round( value, 2 ) end ) as 'Goal 2',max( case when goals='G3' then round( value, 2 ) end ) as 'Goal 3',max( case when goals='G4' then round( value, 2 ) end ) as 'Goal 4' from sgwebdb.dim_module group by alternative";
this.GridView1.DataSource = DataManager.DatabaseManager.GetOrCreateConnection(DataManager.DatabaseManager.ConnectionType.MySQL).GetData(query1);
GridView1.DataBind();
for (int n = 0; n < (GridView1.Rows.Count - 1); n++)
{
Textval.Text = GridView1.Rows[n].Cells[1].Text;
double gdval = Convert.ToDouble(Textval.Text);
}
}
Inplace of Query1 in c# code how can I call above MySQL procedure ?

When you create the MySqlCommand object you need to set the Name of the Stored Procedure in the CommandText property and set the CommandType property to CommandType.StoredProcedure.
Here's a code sample setting up a MySqlCommand object to do just that:
MySqlCommand command = new MySqlCommand();
command.Connection = connection;
command.CommandText = "NameOfYourStoredProcedure";
command.CommandType = CommandType.StoredProcedure;
A little caveat with adding parameters is that the names of the parameters in the stored procedure must match those added to the Parameters collection of the MySqlCommand object.

Related

How to pass a list of strings a sql parameter for the stored procedure to delete?

I've got the following method that is supposed to delete the Holiday names from the database given from the List's that are passed in as arguments. The problem I am having is it isn't deleting anything from the database. Here is part of the method that I am having issues with:
private void RemoveGloOrderDays(List<SessionInfoList> sessionList, List<Holiday> selectedOrderHolidays, List<Holiday> selectedHolidays, List<string> orderDays, List<string> noOrderDays)
{
try
{
using (SqlCommand cmd = new SqlCommand())
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
cmd.CommandTimeout = 600;
cmd.CommandText = "[dbo].[RemoveGlobalOrderDays]";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = connection;
cmd.Parameters.Add("#SessionId", SqlDbType.Int);
cmd.Parameters.Add("#SelectedOrderHolidays", SqlDbType.NVarChar);
cmd.Parameters.Add("#SelectedHolidays", SqlDbType.NVarChar);
cmd.Parameters.Add("#OrderDays", SqlDbType.NVarChar);
cmd.Parameters.Add("#NoOrderDays", SqlDbType.NVarChar);
connection.Open();
foreach (SessionInfoList session in sessionList)
{
cmd.Parameters["#SessionId"].Value = session.SessionID;
cmd.Parameters["#SelectedOrderHolidays"].Value = DBNull.Value;
string joinedNames = string.Join(",", selectedOrderHolidays.Select(h => h.Name.Trim()));
if (!string.IsNullOrEmpty(joinedNames))
{
cmd.Parameters["#SelectedOrderHolidays"].Value = joinedNames;
}
cmd.Parameters["#SelectedHolidays"].Value = DBNull.Value;
joinedNames = string.Join(",", selectedHolidays.Select(h => h.Name.Trim()));
if (!string.IsNullOrEmpty(joinedNames))
{
cmd.Parameters["#SelectedHolidays"].Value = joinedNames;
}
Here is my stored procedure:
IF OBJECT_ID('[dbo].[RemoveGlobalOrderDays]') IS NOT NULL
DROP PROCEDURE [dbo].[RemoveGlobalOrderDays]
GO
CREATE PROCEDURE [dbo].[RemoveGlobalOrderDays]
#SessionId int,
#SelectedHolidays nvarchar(500),
#SelectedOrderHolidays nvarchar(500),
#OrderDays nvarchar(500),
#NoOrderDays nvarchar(500)
WITH ENCRYPTION
AS
BEGIN
SET NOCOUNT ON;
UPDATE [cfgSchedule]
SET
[OrderDays] = #OrderDays,
[NoOrderDays] = #NoOrderDays
WHERE [cfgSchedule].[SessionId] = #SessionID
DELETE FROM [SessionHolidayMapping]
WHERE [HolidayName] = #SelectedHolidays
AND
[SessionId] = #SessionId
DELETE FROM [SessionOrderHolidayMapping]
WHERE [SessionId] = #SessionId
AND
[HolidayName] = #SelectedOrderHolidays
END
GO
As far as I can see you are passing list of names separated by comma and you want to delete all those names. You need to use IN operator to find all holiday names that should be deleted.
Here is an example how to do it for #SelectedHolidays:
declare #SelectedHolidays nvarchar(500) = 'H1,H2,H3'
declare #SelectedHolidaysXml xml = cast(replace(N'<R><I>' + #SelectedHolidays + N'</I></R>', ',', '</I><I>') as xml)
DELETE FROM [SessionHolidayMapping]
WHERE [HolidayName] in (select x.items.value('(.)[1]', 'NVARCHAR(500)') from #SelectedHolidaysXml.nodes('/R/I') as x(items))
AND [SessionId] = #SessionId
It is ugly, but I don't know of better way to split comma separated values in sql server.
Instead of using nvarchar, you could use table valued parameters for the parameters #Selectedholidays and #selectedorderholidays and then something like
DELETE [SessionHolidayMapping] FROM [SessionHolidayMapping] A
Inner join #selectedholidays S
On A.[HolidayName] = S.Holidayname where A.[SessionId] = #SessionId.
The "HolidayName" is one column of the parameter.
I'm on my phone and cannot test it appropriately.

Must declare the scalar variable "#ManagerID"

I have a Running Time Error:
Must declare the scalar variable \"#ManagerID
I'm Sure I Have Declare All Variables In My CLass And My Procudure
My Class Code:
public DataTable Select(int ID,string NameFa, string Address, int ManagerID, short TotalUnits, int ChargeMethodID)
{
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("NameFa", typeof(string));
table.Columns.Add("Address", typeof(string));
table.Columns.Add("ManagerID", typeof(int));
table.Columns.Add("TotalUnits", typeof(short));
table.Columns.Add("ChargeMethodID", typeof(int));
try
{
con.Open();
SqlCommand command = new SqlCommand("dbo.SelectBuilding", con);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#ID", ID));
command.Parameters.Add(new SqlParameter("#NameFa", NameFa));
command.Parameters.Add(new SqlParameter("#Address", Address));
command.Parameters.Add(new SqlParameter("#ManagerID", ManagerID));
command.Parameters.Add(new SqlParameter("#TotalUnits", TotalUnits));
command.Parameters.Add(new SqlParameter("#ChargeMethodID", ChargeMethodID));
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(table);
return table;
}
And My Procudure Code Is:
#ID int,
#NameFa nvarchar(150),
#Address nvarchar(MAX),
#ManagerID int,
#TotalUnits smallint,
#ChargeMethodID int
As
Begin
IF(#ID >0 )
Begin
Select ID,NameFa,Address,ManagerID,TotalUnits,ChargeMethodID From Buildings where ID = #ID
End
ELSE
Begin
Declare #sqlTxt nvarchar(MAX)
SET #sqlTxt = 'SELECT ID,NameFa,Address,ManagerID,TotalUnits,ChargeMethodID FROM Buildings where ID>0'
IF(#NameFa!= null)
BEGIN
SET #sqlTxt = #sqlTxt + ' AND NameFa Like ''%#NameFa%'''
END
IF(#Address!= null)
BEGIN
SET #sqlTxt = #sqlTxt + ' AND Address Like ''%#Address%'''
END
IF(#ManagerID > 0)
BEGIN
SET #sqlTxt = #sqlTxt + ' AND ManagerID = #ManagerID'
END
IF(#TotalUnits > 0)
BEGIN
SET #sqlTxt = #sqlTxt + ' AND TotalUnits = #TotalUnits'
END
IF(#ChargeMethodID > 0)
BEGIN
SET #sqlTxt = #sqlTxt + ' AND ChargeMethodID = #ChargeMethodID'
END
EXEC (#sqlTxt);
End
END
And I want to use Select Function:
DataTable dt = new DataTable();
Buildings.Building bb = new Buildings.Building() {ID=0,NameFa="",Address="",ManagerID=OwnerID,TotalUnits=0,ChargeMethodID=0 };
dt = bu.Select(bb.ID,bb.NameFa,bb.Address,bb.ManagerID,bb.TotalUnits,bb.ChargeMethodID);
You are not passing the parameters to the exec statement. I would change it to sp_executesql which has an optional argument with parameters.
https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql
Edit: I strongly suggest getting rid of the exec and/or sp_executesql commands. Because depending on the input you could:
a) Get runtime errors due to user typing SQL string delimiters as a valid input. Example O'Hara as a surname.
b) A malicious user could mess badly with your database.
You could get similar result in a more simple way:
Select
ID,NameFa,Address,ManagerID,TotalUnits,ChargeMethodID
From
Buildings
where
(#Id = 0 or ID = #Id)
and (#NameFa = '' or NameFa = #NameFa)
and (#ManagerID = 0 or ManagerID = #ManagerID)
// repeat for the rest of the optional search conditions

Error CODE : procedure has too many arguments specified

I have a this SQL Server stored procedure. When I execute it, I'm getting this error:
SQL Server procedure has too many arguments specified
How can I solve this problem? Code is shown below.
When my stored procedure is working, I need to do if record exist update then add record.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Insert_MS]
(#SID char(20),
#CREATE_DATETIME char(14),
#MODIFY_DATETIME char(14),
#CREATOR_SID char(20),
#MODIFIER_SID char(20),
#MARK_DELETED char(1),
#TARGET_SID nvarchar(20),
#TARGET_CODE nvarchar(50),
#UNIT nvarchar(100),
#SPECIFICATION nvarchar(1000),
#MATERIALS_SUBCAT nvarchar(1000),
#SORT int,
#SET_UNIT nvarchar(1000),
#ENABLED char(1),
#MARKET_TYPE nvarchar(2)
)
AS
BEGIN
IF EXISTS (SELECT *
FROM [dbo].[M_S]
WHERE [MARKET_TYPE] = #MARKET_TYPE
AND [TARGET_CODE] = #TARGET_CODE
AND [TARGET_SID] = #TARGET_SID)
BEGIN
--update existing record
UPDATE [dbo].[M_S]
SET [MATERIALS_SUBCAT] = #MATERIALS_SUBCAT ,
[SPECIFICATION] = #SPECIFICATION,
[UNIT] = #UNIT
WHERE [MARKET_TYPE] = #MARKET_TYPE
AND [TARGET_CODE] = #TARGET_CODE
AND [TARGET_SID] = #TARGET_SID
END
ELSE
BEGIN
--insert new record
INSERT INTO [dbo].[M_S] ([SID], [CREATE_DATETIME], [MODIFY_DATETIME],
[CREATOR_SID], [MODIFIER_SID], [MARK_DELETED],
[TARGET_SID], [TARGET_CODE], [UNIT], [SPECIFICATION],
[MATERIALS_SUBCAT], [SORT], [SET_UNIT],
[ENABLED], [MARKET_TYPE])
VALUES (#SID, #CREATE_DATETIME, #MODIFY_DATETIME,
#CREATOR_SID, #MODIFIER_SID, #MARK_DELETED,
#TARGET_SID, #TARGET_CODE, #UNIT,
#SPECIFICATION,
#MATERIALS_SUBCAT, #SORT, #SET_UNIT,
#ENABLED, #MARKET_TYPE)
END
END
Then my aspx.cs code is here
cnn.Open();
insertSql += " INSERT INTO [dbo].[MATERIALS_SUBCAT] ([SID],[CREATE_DATETIME], [MODIFY_DATETIME],";
insertSql += " [CREATOR_SID], [MODIFIER_SID], [MARK_DELETED],[TARGET_SID], [TARGET_CODE],";
insertSql += " [UNIT], [SPECIFICATION], [MATERIALS_SUBCAT], [SORT],[SET_UNIT], [ENABLED], [MARKET_TYPE])";
insertSql += " VALUES (#SID, #CREATE_DATETIME, #MODIFY_DATETIME, #CREATOR_SID, #MODIFIER_SID, #MARK_DELETED, #TARGET_SID, #TARGET_CODE, #UNIT, #SPECIFICATION,";
insertSql += "#MATERIALS_SUBCAT, #SORT, #SET_UNIT, #ENABLED, #MARKET_TYPE) ";
SqlCommand cmdStoredProcedure = new SqlCommand("Insert_MS", cnn);
cmdStoredProcedure.CommandType = CommandType.StoredProcedure;
for (int k = 0; k <= dt_sheet.Rows.Count - 1; k++)
{
cmdStoredProcedure.Parameters.AddWithValue("#SID", dt_sheet.Rows[k]["SID"].ToString());
cmdStoredProcedure.Parameters.AddWithValue("#CREATE_DATETIME", dt_sheet.Rows[k]["CREATE_DATETIME"].ToString());
cmdStoredProcedure.Parameters.AddWithValue("#MODIFY_DATETIME", dt_sheet.Rows[k]["MODIFY_DATETIME"].ToString());
cmdStoredProcedure.Parameters.AddWithValue("#CREATOR_SID", dt_sheet.Rows[k]["CREATOR_SID"].ToString());
cmdStoredProcedure.Parameters.AddWithValue("#MODIFIER_SID", dt_sheet.Rows[k]["MODIFIER_SID"].ToString());
cmdStoredProcedure.Parameters.AddWithValue("#MARK_DELETED", dt_sheet.Rows[k]["MARK_DELETED"].ToString());
cmdStoredProcedure.Parameters.AddWithValue("#TARGET_SID", dt_sheet.Rows[k]["分類代碼"].ToString());
cmdStoredProcedure.Parameters.AddWithValue("#TARGET_CODE", dt_sheet.Rows[k]["品項代碼"].ToString());
cmdStoredProcedure.Parameters.AddWithValue("#UNIT", dt_sheet.Rows[k]["單位"].ToString());
cmdStoredProcedure.Parameters.AddWithValue("#SPECIFICATION", dt_sheet.Rows[k]["規格"].ToString());
cmdStoredProcedure.Parameters.AddWithValue("#MATERIALS_SUBCAT", dt_sheet.Rows[k]["品項名稱"].ToString());
cmdStoredProcedure.Parameters.AddWithValue("#SORT", dt_sheet.Rows[k]["SORT"].ToString());
cmdStoredProcedure.Parameters.AddWithValue("#SET_UNIT",null);
cmdStoredProcedure.Parameters.AddWithValue("#ENABLED", dt_sheet.Rows[k]["ENABLED"].ToString());
cmdStoredProcedure.Parameters.AddWithValue("#MARKET_TYPE", dt_sheet.Rows[k]["MARKET_TYPE"].ToString());
cmdStoredProcedure.ExecuteNonQuery();
cnn.Close();
}
Seems like you want to execute the stored procedure each time you loop through your sheet. Moving the Command into the loop and use "using" to easy dispose the command each time, like this:
for (int k = 0; k <= dt_sheet.Rows.Count - 1; k++)
{
using (SqlCommand cmdStoreProcedure = new SqlCommand("Insert_MS", cnn))
{
cmdStoreProcedure.CommandType = CommandType.StoredProcedure;
cmdStoreProcedure.Parameters.AddWithValue("#SID", dt_sheet.Rows[k]["SID"].ToString());
cmdStoreProcedure.Parameters.AddWithValue("#CREATE_DATETIME", dt_sheet.Rows[k]["CREATE_DATETIME"].ToString());
cmdStoreProcedure.Parameters.AddWithValue("#MODIFY_DATETIME", dt_sheet.Rows[k]["MODIFY_DATETIME"].ToString());
cmdStoreProcedure.Parameters.AddWithValue("#CREATOR_SID", dt_sheet.Rows[k]["CREATOR_SID"].ToString());
cmdStoreProcedure.Parameters.AddWithValue("#MODIFIER_SID", dt_sheet.Rows[k]["MODIFIER_SID"].ToString());
cmdStoreProcedure.Parameters.AddWithValue("#MARK_DELETED", dt_sheet.Rows[k]["MARK_DELETED"].ToString());
cmdStoreProcedure.Parameters.AddWithValue("#TARGET_SID", dt_sheet.Rows[k]["分類代碼"].ToString());
cmdStoreProcedure.Parameters.AddWithValue("#TARGET_CODE", dt_sheet.Rows[k]["品項代碼"].ToString());
cmdStoreProcedure.Parameters.AddWithValue("#UNIT", dt_sheet.Rows[k]["單位"].ToString());
cmdStoreProcedure.Parameters.AddWithValue("#SPECIFICATION", dt_sheet.Rows[k]["規格"].ToString());
cmdStoreProcedure.Parameters.AddWithValue("#MATERIALS_SUBCAT", dt_sheet.Rows[k]["品項名稱"].ToString());
cmdStoreProcedure.Parameters.AddWithValue("#SORT", dt_sheet.Rows[k]["SORT"].ToString());
cmdStoreProcedure.Parameters.AddWithValue("#SET_UNIT", null);
cmdStoreProcedure.Parameters.AddWithValue("#ENABLED", dt_sheet.Rows[k]["ENABLED"].ToString());
cmdStoreProcedure.Parameters.AddWithValue("#MARKET_TYPE", dt_sheet.Rows[k]["MARKET_TYPE"].ToString());
// connection.Open();
cmdStoreProcedure.ExecuteNonQuery();
}
}
cnn.Close();
Your code tries to access SQL Commmand: Insert_Materials_SubCategory
Whereas the shown procedure is called: Insert_MS

Building dynamic sql query with between and order by key word

I have a situation where parameter to my sql query would be dynamic.if parameter is null i don't want to add it to the query,I have tried some thing(never worked)..and it look like stoopid to me now
ds = SqlHelper.ExecuteDataset(GlobalSettings.DbDSN, CommandType.Text, "SELECT TOP 1000 [ID],[Project],[Owner],[Consultant],[Contractor],[Value],[Level1],[Level2] ,[Status] ,[Category] ,[Country],[CreatedDate],[CreatedByID],[CreatedByName] FROM [tbl_Projects] where"+if(!string.IsNullOrEmpty(paraCategory)){ "[Category] = #Category and"}+"+ Country =#country and "+if(!string.IsNullOrEmpty(paraCategory)){ " value between #val1 and #val2"}+" order by CreatedDate asc",
new SqlParameter("#Category", paraCategory),
new SqlParameter("#Country", paraCountry),
new SqlParameter("#val1", paraValue1),
new SqlParameter("#val2", paraValue2));
I have checked Building dynamic sql also
here
But it is not usefull where I need to put like and between key words..can any one give me a hand on this?
Just to give you an idea, I would do something like this:
var sql as new StringBuilder();
sql.Append("SELECT ... all your columns ... FROM yourTable");
var parameters as new List(Of SqlParameter);
if (!string.IsNullOrEmpty(paraCategory)
{
sql.Append("[Category]=#Category,");
parameters.AddWithvalue("#Category", paraCategory);
}
sql.Length -= 1
//...your other parameters...
sql.Append("ORDER BY CreatedDate");
And then pass it all to your SqlHelper:
ds = SqlHelper.ExecuteDataset(GlobalSettings.DbDSN, CommandType.Text, sql.ToString(), parameters);
Also note that the above code is not really defensive. So for example if no parameter is delivered it will fail. And since I don't know the SqlHelper-Class, you might need to have something else than a List(Of SqlParameter).
Change SqlHelper.ExecuteDatasetso that it takes a delegate to call the specific code you want:
class SqlHelper
{
public delegate void SqlCommandDelegate(SqlCommand command);
public Dataset ExecuteDataset(string dsn,
CommandType commandType,
SqlCommandDelegate specificPreparations)
{
Dataset results;
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = dsn;
using (SqlCommand command = conn.CreateCommand())
{
command.CommandType = commandType;
connection.Open();
specificPreparations(command);
SqlDataReader reader = command.ExecuteReader();
results.Load(reader);
}
}
return results;
}
}
Then to call it:
ds = SqlHelper.ExecuteDataset(GlobalSettings.DbDSN,
CommandType.Text,
delegate(SqlCommand command)
{
command.CommandText = "SELECT BLAH FROM BLAH";
foreach (var myParameter in myParameterList)
{
SqlParameter p = new SqlParameter();
// Construct p
command.Paramters.Add(p)
}
// Anything else you want to do to the command
});
}
you can do this using a SP
CREATE PROCEDURE MyDynamicSP(#Condition1 as varchar(100),Condition2 as varchar(100),Condition3 as varchar(100))
AS
SET NOCOUNT ON
DECLARE #STRSQL VARCHAR(1000)
SET #STRSQL = 'SELECT * FROM MyTable WHERE '
IF NOT #Condition1 IS NULL
#STRSQL = #STRSQL + ' ' + #Condition1
IF NOT #Condition2 IS NULL
#STRSQL = #STRSQL + ' ' + #Condition2
IF NOT #Condition3 IS NULL
#STRSQL = #STRSQL + ' ' + #Condition3
EXEC sp_executesql #STRSQL
SET NOCOUNT OFF
You can do the testing inside the query as such :
SELECT *whatever you need*
FROM [tbl_Projects]
where
(#Category is null or [Category] = #Category) and
(#Country is null or [Country] = #country) and
(#val1 is null or value > #val1) and
(#val2 is null or value < #val2)
order by CreatedDate asc
And you always send the 4 parameters. On the plus side, you can build your query in a SQL worksheet and it's easier to spot syntax errors an so on.
You might need to add some tests for what would be an empty value, though.

Pass table valued parameter using ADO.NET

How to pass table valued parameter to stored procedure using ADO.NET?
Create type in SQL Server:
CREATE TYPE [dbo].[MyDataType] As Table
(
ID INT,
Name NVARCHAR(50)
)
Create Procedure:
CREATE PROCEDURE [dbo].[MyProcedure]
(
#myData As [dbo].[MyDataType] Readonly
)
AS
BEGIN
SELECT * FROM #myData
END
Create DataTable in C#:
DataTable myDataTable = new DataTable("MyDataType");
myDataTable.Columns.Add("Name", typeof(string));
myDataTable.Columns.Add("Id", typeof(Int32));
myDataTable.Rows.Add("XYZ", 1);
myDataTable.Rows.Add("ABC", 2);
Create SQL Parameter:
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "#myData";
parameter.SqlDbType = System.Data.SqlDbType.Structured;
parameter.Value = myDataTable;
command.Parameters.Add(parameter);
I tried this and received the exception:
The table type parameter '#MyDataType' must have a valid type name.
I had to set the "TypeName" property of the SqlParameter:
parameter.TypeName = "MyDataType";
This question is a duplicate of How to pass table value parameters to stored procedure from .net code. Please see that question for an example illustrating the use of either a DataTable or an IEnumerable<SqlDataRecord>.
For multilinguals, a little late to the show:
a) elsewhere on tsql
--- create a vector data type
CREATE TYPE [dbo].[ItemList] AS TABLE([Item] [varchar](255) NULL)
b)
Dim Invoices As New DataTable("dbo.ItemList") 'table name is irrelevant
Invoices.Columns.Add("Invoice", GetType(String))
...
With .SqlCommand.Parameters
.Clear()
.Add(New Data.SqlClient.SqlParameter() With {
.SqlDbType = Data.SqlDbType.Structured,
.Direction = Data.ParameterDirection.Input,
.ParameterName = "#Invoices",
.TypeName = "dbo.ItemList",
.Value = Invoices})
End With
...
' using store procedure
.CommandText = "SELECT * FROM dbo.rpt(#invoices) "
' or direct reference is a select
.CommandText = "SELECT * FROM dbo.invoicedata" +
"where ((select count(*) from #invoices) = 0 or "+
"InvoiceNumber in (select distinct * from #Invoices))
You can prefix with Exec
using( SqlConnection con = new SqlConnection( "Server=.;database=employee;user=sa;password=12345" ) )
{
SqlCommand cmd = new SqlCommand( " exec ('drop table '+#tab)" , con );
cmd.Parameters.AddWithValue( "#tab" ,"Employee" );
con.Open( );
cmd.ExecuteNonQuery( );
}

Categories