I have create procedure code. When I try run create procedure codes in phpmyadmin, it is works. But when I try run in c#, it is return error like that:
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 'DELIMITER !!
Create Procedure Code:
DELIMITER ;;
CREATE DEFINER=`root`#`localhost` PROCEDURE `update_alldoctorname`(IN `p_doktor` VARCHAR(65) CHARSET latin5, IN `p_eski` VARCHAR(65) CHARSET latin5)
NO SQL
BEGIN
UPDATE users SET hekim=p_doktor WHERE hekim=p_eski;
UPDATE tedavi SET tedavi_doktor=p_doktor WHERE tedavi_doktor=p_eski;
UPDATE medikal SET doktor=p_doktor WHERE doktor=p_eski;
UPDATE cek_devreden SET unvan=p_doktor WHERE unvan=p_eski;
END
;;
DELIMITER ;
How can I fix it?
You can't use the DELIMITER ;; syntax with MySqlCommand in C#. Instead, just use the body of the CREATE PROCEDURE statement as the MySqlCommand.CommandText and execute it:
using (var command = yourConnection.CreateCommand())
{
command.CommandText = #"CREATE DEFINER=`root`#`localhost` PROCEDURE `update_alldoctorname`(IN `p_doktor` VARCHAR(65) CHARSET latin5, IN `p_eski` VARCHAR(65) CHARSET latin5)
NO SQL
BEGIN
UPDATE users SET hekim=p_doktor WHERE hekim=p_eski;
UPDATE tedavi SET tedavi_doktor=p_doktor WHERE tedavi_doktor=p_eski;
UPDATE medikal SET doktor=p_doktor WHERE doktor=p_eski;
UPDATE cek_devreden SET unvan=p_doktor WHERE unvan=p_eski;
END";
command.ExecuteNonQuery();
}
Related
I'm trying to write a stored procedure to determine the number of connections on the active database. My stored procedure is currently as follows:
CREATE PROCEDURE [dbo].[GetActiveUsers]
AS
BEGIN
SET NOCOUNT ON;
DECLARE #who TABLE(spid SMALLINT, ecid SMALLINT, [status] NCHAR(30), loginame NCHAR(128), hostname NCHAR(128), blk CHAR(5), dbname NCHAR(128), cmd NCHAR(16), request_id INT);
INSERT INTO #who
exec sp_who 'FMApp'
--SELECT 99,98,'good','person','host','12345','db','1234567890123456',1
SELECT COUNT(*) AS [ActiveUsers] FROM #who;
END
The reason I am putting the results of sp_who into a table variable is so that I can do some further filtering on the results. I've removed the filtering for now for the sake of debugging.
When I call this stored procedure through SQL Server Management Studio it behaves as expected and I get a non zero value. When I call it through C# using a SqlCommand however it always returns zero.
Calling code:
*Note: connectionService.Create returns an open SqlConnection
using (var connection = connectionService.Create())
{
var activeUsersSql = "GetActiveUsers";
using (var command = new SqlCommand(activeUsersSql, connection))
{
command.CommandType = CommandType.StoredProcedure;
using (var reader = command.ExecuteReader())
{
if (reader.Read())
{
activeUsers = reader.GetInt32(0);
}
}
}
}
If I alter my stored procedure to populate my table variable from a source other than sp_who then both the call to SSMS and the call through SqlCommand agree on the result.
CREATE PROCEDURE [dbo].[GetActiveUsers]
AS
BEGIN
SET NOCOUNT ON;
DECLARE #who TABLE(spid SMALLINT, ecid SMALLINT, [status] NCHAR(30), loginame NCHAR(128), hostname NCHAR(128), blk CHAR(5), dbname NCHAR(128), cmd NCHAR(16), request_id INT);
INSERT INTO #who
SELECT 99,98,'good','person','host','12345','db','1234567890123456',1
--exec sp_who 'FMApp'
SELECT COUNT(*) AS [ActiveUsers] FROM #who;
END
Is it an issues of permissions, a restriction on the use of sp_* procedures or am I missing something obvious?
As suggested by #DavidG the issue was one of permissions. Without the VIEW SERVER STATE permission you can only view your own session. The user I was filtering by was different from the one I was running the process as so it always came up as zero.
To view or retrieve results from sp_who/sp_who2 should need VIEW SERVER STATE permission. I you are using administrator account to connect to SQL server via your C# application it should return data. Check the permission assigned with the account that you use to connect to SQL server in your application.
If no permission, user will be able to see only current session.
I am new to programming in Visual Studio C#. I have been trying to create a table using a Stored Procedure. When I try to update the table, I get an error.
The Stored Procedure script is as follows:
CREATE TABLE [dbo].[Table]
(
[Id] INT NOT NULL PRIMARY KEY,
[Error] VARCHAR(30) NULL
)
GO
CREATE PROCEDURE [dbo].[InsertLog]
(
#error varchar(30)
)
AS
INSERT INTO [dbo].[Table]
(
[Error]
)
VALUES
(
#error
)
GO
My connection string is as follows:
connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf;Persist Security Info=true;Integrated Security=True;"
The error I get when updating the table is as follows:
I am using the LocalDB and I have no login credentials. Kindly help me with the error.
Note: I also went through other StackOverflow questions and none helped.
Thanks
I think you can refer to the following steps to execute the stored procedure.
First, you can create table like the following picture. Here I want to mention that you
need to use automatic increment if you want to use the stored procedure you provided.
Also, you can not create stored procedure here.
Second, click database->choose Programmability->choose stored procedures-> right click Add new procedure like the following:
CREATE PROCEDURE [dbo].[InsertLog]
(
#error varchar(30)
)
AS
INSERT INTO [dbo].[Newtable]
(
[Error]
)
VALUES
(
#error
)
Finally, you can use the following code to call stored procedure in c#.
string connectionstring = #"Connectionstring";
SqlConnection connection = new SqlConnection(connectionstring);
connection.Open();
SqlCommand command = new SqlCommand("InsertLog",connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#error", textBox1.Text);
command.ExecuteNonQuery();
connection.Close();
How have you mentioned your connection string? COuld you please add that as well
I am working on a program in c# where I have a layout as shown in the image below:
The purpose of the program is to perform data archiving in SQL server. If I choose "Create Tables", it will generate new tables into my database ( should generate about 40 tables in order) which has similar table structure (columns,constraint,triggers,etc) as original tables in the same database as well. How this works is I'll execute the SQL scripts in c# and call them (all 40 scripts) to create tables.
Right now, I added another button "Transfer data" where it will select specfic data(based on date) in old data and transfer them into the new tables I created. I will use the query Insert Into....SELECT from to transfer data.
My question is should I create sql scripts for transferring data and execute them in c# or just put the SQL queries inside my c# code ?
If I go with SQL scripts, should I split them into 40 scripts as well or place all the queries inside 1 script? I know it will be tedious if i put everything in one script as if an error occurs, it's hard to trace the source of the problem.
Below is a sample of how the sql query looks like :
SET IDENTITY_INSERT Kiosk_Log_New ON
INSERT INTO Kiosk_Log_New(LOGID,
logAPPID,
logLOGTID,
logGUID,
logOriginator,
logReference,
logAssemblyName,
logFunctionName,
logMessage,
logException,
CreatedBy,
CreatedDate)
SELECT LOGID,
logAPPID,
logLOGTID,
logGUID,
logOriginator,
logReference,
logAssemblyName,
logFunctionName,
logMessage,
logException,
CreatedBy,
CreatedDate FROM Kiosk_Log
WHERE CreatedDate BETWEEN '2015-01-01' AND GETDATE()
EDIT: Since many suggested stored procedure is the best option, this would be my create tables script:
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
/* open sql connection to execute SQL script: PromotionEvent_New */
try
{
using (SqlConnection con = new SqlConnection(constr))
{
con.Open();
FileInfo file = new FileInfo("C:\\Users\\88106221\\Documents\\SQL Server Management Studio\\PromotionEvent_New.sql");
string script = file.OpenText().ReadToEnd();
Server server = new Server(new ServerConnection(con));
server.ConnectionContext.ExecuteNonQuery(script);
Display("PromotionEvent_New table has been created successfully");
con.Close();
}
}
catch(Exception ex)
{
textBox1.AppendText(string.Format("{0}", Environment.NewLine));
textBox1.AppendText(string.Format("{0} MainPage_Load() exception - {1}{2}", _strThisAppName, ex.Message, Environment.NewLine));
Display(ex.Message + "PromotionEvent_New could not be created");
textBox1.AppendText(string.Format("{0}", Environment.NewLine));
Debug.WriteLine(string.Format("{0} MainPage_Load() exception - {1}", _strThisAppName, ex.Message));
}
It's best to use a stored procedure with a transaction to execute all your INSERT queries.
It's not advisable to submit queries from your C# code as explained in last post by John Ephraim Tugado due to a number of reasons; the most important reasons being,
easier maintenance of INSERT queries
minimal bandwidth consumption between web server and database server
Sending long queries strings from C# code will consume more bandwidth between web server and database server and could slow the database response in a high traffic scenario.
You can execute the following T-SQL code against your database to create a stored procedure for transferring/archiving data to archived tables. This procedure makes sure that all your INSERTS are executed within a transaction, that ensures you don't end up with orphaned tables and unnecessary headaches down the road.
Stored Procedure for transferring data
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Lord Cookie
-- Create date: 11/01/2017
-- Description: Transfers data to existing archived tables
-- =============================================
CREATE PROCEDURE dbo.ArchiveData
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
--use transaction when inserting data else you may end up with orphaned data and hard to debug issues later on
BEGIN TRANSACTION
--add your INSERT queries one after the other below
SET IDENTITY_INSERT Kiosk_Log_New ON
INSERT INTO Kiosk_Log_New (LOGID,
logAPPID,
logLOGTID,
logGUID,
logOriginator,
logReference,
logAssemblyName,
logFunctionName,
logMessage,
logException,
CreatedBy,
CreatedDate)
SELECT
LOGID
,logAPPID
,logLOGTID
,logGUID
,logOriginator
,logReference
,logAssemblyName
,logFunctionName
,logMessage
,logException
,CreatedBy
,CreatedDate
FROM Kiosk_Log
WHERE CreatedDate BETWEEN '2015-01-01' AND GETDATE()
--add more of your insert queries below
-- finally commit transaction
COMMIT TRANSACTION
END TRY
BEGIN CATCH
DECLARE #errorDetails NVARCHAR(MAX);
set #errorDetails = 'Error ' + CONVERT(VARCHAR(50), ERROR_NUMBER()) +
', Severity ' + CONVERT(VARCHAR(5), ERROR_SEVERITY()) +
', State ' + CONVERT(VARCHAR(5), ERROR_STATE()) +
', Line ' + CONVERT(VARCHAR(5), ERROR_LINE());
--roll back the transaction
IF XACT_STATE() <> 0
BEGIN
ROLLBACK TRANSACTION
END
--you can log the above error message and/or re-throw the error so your C# code will see an error
--but do this only after rolling back
END CATCH;
END
GO
You can then call the above stored procedure using C# as shown in sample code below.
Call above stored procedure using C#
using(SqlConnection sqlConn = new SqlConnection("Your database Connection String")) {
using(SqlCommand cmd = new SqlCommand()) {
cmd.CommandText = "dbo.ArchiveData";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConn;
sqlConn.Open();
cmd.ExecuteNonQuery();
}
}
Depending on the table naming and design, I would suggest creating a script to create a stored procedure for this that would generate one for each of your tables. I'm no expert in scripting but it is the same with the script that generates an audit trail for each of your tables or at least the ones you defined in the script.
Hard-coding this inside your c# application is a big NO as there is the possibility of database changes. We would want our app to be flexible to change with the least amount of effort.
If generating the script to create a stored procedure is hard for you, I would still recommend manually creating stored procedures for this task.
I'm having problems to run a script inside a custom action. The script creates and sets up a database in a localhost MySQL server.
Concretely, I have problems with one of my procedures:
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `UpdateAutoInc`(IN `increment` BIGINT)
BEGIN
SET #s = concat('ALTER TABLE tblactionservices AUTO_INCREMENT ',increment);
PREPARE stmt FROM #s;
EXECUTE stmt;
SET #s = concat('ALTER TABLE tblbannedclient AUTO_INCREMENT ',increment);
PREPARE stmt FROM #s;
EXECUTE stmt;
END$$
DELIMITER ;
In the script, before this procedure, I have 2 other procedures that run perfectly.
The error I get when I install the application is "Parameter '#s' must be defined". Looking for the Internet I found this blog but I added the "Allow User Variables=True;" with no luck. With this piece of text, the script crashes directly on the first procedure. Indeed, it crashes always, no matter what it finds (procedures, tables...). The error I get is absolutely useless "You have an error in your SQL Syntax; check the manual bla bla", so I can't find the problem.
This is the class I'm using to run the script from c#:
private void ExecuteSql(string DatabaseName, string Sql)
{
MySqlConnection connection = new MySqlConnection { ConnectionString = "server=127.0.0.1;User Id=root" };
MySqlCommand command = new MySqlCommand(Sql, connection);
command.Connection.Close();
command.Connection.Open();
try
{
command.ExecuteNonQuery();
}
finally
{
// Closing the connection should be done in a Finally block
command.Connection.Close();
}
}
The script wasn't manually typed but it was automatically generated from PhPMyAdmin. The version of MySQL server is 5.5 and the connector version is 6.5.5.0
I am writing a CLR Update trigger for SQL Server 2008 R2. The trigger needs to write updated values to a table in another database hosted in the same SQL Server instance. When I try to open a connection created with the following connection string from within my trigger I get a "SecurityException":
...new SqlConnection("Data Source=(local);Initial Catalog=[my database];Integrated Security=True")
It is highly desirable that I leave my assembly's permission level as SAFE. I am pretty sure that I'd have to set my assembly's permission level to EXTERNAL_ACCESS to connect to a remote database, but is it possible to connect to another database in the same SQL Server instance with the SAFE permission level?
Thanks.
Yes, it is definitely possible to reference another database in a SQLCLR trigger that resides inside of an Assembly marked as SAFE. The error encountered in the question is due simply to using a regular / external connection string, which requires a PERMISSION_SET of EXTERNAL_ACCESS. But using the in-process / internal connection string of "Context Connection = true;" allows you to run whatever query you want, including a query that references another database via 3-part object name.
I was able to do this with the following code:
Main Table (in TestDB1):
CREATE TABLE dbo.Stuff
(
[Id] INT IDENTITY(1, 1) NOT NULL PRIMARY KEY,
[Something] NVARCHAR(50) NOT NULL
);
Audit Table (in TestDB2):
CREATE TABLE dbo.AuditLog
(
AuditLogID INT IDENTITY(1, 1) NOT NULL PRIMARY KEY,
EventTime DATETIME NOT NULL DEFAULT (GETDATE()),
BeforeValue NVARCHAR(50) NULL,
AfterValue NVARCHAR(50) NULL
);
SQLCLR Trigger on main table (partial code):
string _AuditSQL = #"
INSERT INTO TestDB2.dbo.AuditLog (BeforeValue, AfterValue)
SELECT del.Something, ins.Something
FROM INSERTED ins
FULL OUTER JOIN DELETED del
ON del.Id = ins.Id;
";
SqlConnection _Connection = new SqlConnection("Context Connection = true");
SqlCommand _Command = _Connection.CreateCommand();
_Command.CommandText = _AuditSQL;
try
{
_Connection.Open();
_Command.ExecuteNonQuery();
}
finally
{
_Command.Dispose();
_Connection.Dispose();
}
Test queries:
USE [TestDB1];
SELECT * FROM dbo.Stuff;
---
INSERT INTO dbo.Stuff (Something) VALUES ('qwerty');
INSERT INTO dbo.Stuff (Something) VALUES ('asdf');
SELECT * FROM dbo.Stuff;
SELECT * FROM TestDB2.dbo.AuditLog;
---
UPDATE tab
SET tab.Something = 'dfgdfgdfgdfgdfgdfgd'
FROM dbo.Stuff tab
WHERE tab.Id = 2;
SELECT * FROM dbo.Stuff;
SELECT * FROM TestDB2.dbo.AuditLog;
It looks like it's not possible. However a T-SQL statement can reference another database in the same instance by using [DatabaseName].[dbo].[TableName]. I can do the messy logic in my CLR trigger, then do a final insert into the second database by calling a simple T-SQL stored procedure and passing in parameters.