Target database schema could not be retrieved - Visual Studio Error - c#

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

Related

Why does a tsql stored proceedure that calls sp_who return different results when called through SqlCommnad than it does through SSMS?

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.

Mysql delimiter syntax error only get error on c#

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();
}

MySQL and C#.Net Stored Procedure and multiple parameter

I am developing (converting application db from MS SQL to MySQL) an application using C#.Net and MySQL. My C# code and stored procedure is working perfect in MS SQL but when trying to ingrate with MySQL getting parameter error. My C# Code is as below and MySQL Stored Procedure is running perfectly (tested in editor using CALL key work and parameter)
public DataTable AlapValidateUser(string email, string password,string Type)
{
DataTable dt = new DataTable();
cmd = new MySqlCommand("UserIdValidation");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = cnn;
string pass = reEncryptpassword(password);
MySqlParameter pramEmail = new MySqlParameter("#v_emailId", email);
pramEmail.Direction = ParameterDirection.Input;
cmd.Parameters.Add(pramEmail);
MySqlParameter pramPassword = new MySqlParameter("#v_password", pass);
pramPassword.Direction = ParameterDirection.Input;
cmd.Parameters.Add(pramPassword);
MySqlDataAdapter adap = new MySqlDataAdapter(cmd);
if (cnn.State != ConnectionState.Open ||
cnn.State == ConnectionState.Broken ||
cnn.State != ConnectionState.Connecting ||
cnn.State != ConnectionState.Executing ||
cnn.State != ConnectionState.Fetching)
cnn.Open();
adap.Fill(dt);
cnn.Close();
return dt;
}
MySQL Stored Procedure is here:
CREATE DEFINER=`root`#`localhost` PROCEDURE `UserIdValidation`(v_emailId NATIONAL VARCHAR(100),v_password
NATIONAL VARCHAR(50))
BEGIN
SELECT UserId ,eMail,BloodGroup
,BloodGroupID,Country AS CountrySlNo ,CountryName ,State ,District
,Location,fName,lName ,DonorType ,LastLogIn ,Validated ,ProfileImage
,MaritalStatus ,Sex ,Height ,Weight ,HealthStatus
,MyFileLocation FROM vwUser WHERE eMail = v_emailId AND
PASSWORD = v_password AND Validated = 'Y';
END$$
During execution exception as below:
Incorrect number of arguments for PROCEDURE alap.UserIdValidation; expected 2, got 1
Can you please help me to find out the error.
UPDATE: My MySQL connector is v.6.6.5. I have checked in debug mode in C# parameter is correct and can see both parameter in command object. Next it is trying to filling Adapter hence this command object is passing to MySQL from Connector and there parameter is missing. I have tried to add same 1st parameter by creating 3rd line then getting error that same parameter already exist.
From this test I am sure it is purely MySQL or mysql connector bug.
I don't know how this bug can exists in such DB where so many people is using mysql.
This is a BUG of MY SQL and I have received solution from MySQL Team. I have implemented this changes in my MySQL Stored Procedure and got solution. MySQL reply as below
Hi Suman,
I have reproduced the issue you described, and exists a workaround that
works perfectly fine and hopefully it will keep you up to speed in your
migration to MySql. The problem here is the NATIONAL usage in the
definition of the parameters for the routine. If you want to define a
particular character set you can define the routine like this:
CREATE DEFINER=`root`#`localhost` PROCEDURE
`UserIdValidation`(v_emailId VARCHAR(100) ***CHARACTER SET utf8***,v_password
VARCHAR(50) CHARACTER SET utf8)
BEGIN
.... rest of code
Or you just can use
CREATE DEFINER=`root`#`localhost` PROCEDURE
`UserIdValidation`(v_emailId VARCHAR(100),v_password VARCHAR(50))
BEGIN
....
The default character set in the server is utf8 and is equivalent to
NATIONAL according to the documentation.
You can check more information here:
http://dev.mysql.com/doc/refman/5.5/en/charset-national.html
Please let me know if the workaround worked for you.
I think you might need to change the way you call the stored proc.
Take a look at this example http://forums.asp.net/t/988462.aspx

Parameter '#s' must be defined

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

Connect to another database in SQL Server instance from within 'Safe' CLR database trigger

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.

Categories

Resources