I wrote this code, but it doesn't work. Gives Invalid object name 'Inventory'`. Any Suggestion?
using (SqlConnection cn = new SqlConnection())
{
cn.ConnectionString =
#"Data Source=(local);Integrated Security=SSPI;" +
"Initial Catalog=AutoLot";
cn.Open();
string strSQL = "Select * From Inventory";
SqlCommand myCommand = new SqlCommand(strSQL, cn);
// Obtain a data reader a la ExecuteReader().
using (SqlDataReader mydatareader = mycommand.ExecuteReader())
{}
Check in Database Inventory table is present or not and if Present then both name should be same
If you've checked all your database settings, access rights and table definitions and still cannot get rid of that error?
It's because ASP.net cannot understand your SQL query - as shocking as that may sound.
I had the same problem, with UPDATE statements wanting to use aliases and not the usually expected dbo.myTable name definitions.
The simplest way to avoid this situation, where asp.net just doesn't parse SQL like SQL Server would (!!), is to place the code into a Stored Procedure.
This was my SQL directly from SQL Server 2005 and it worked perfectly as is...
UPDATE tsa
SET tsa.ActionComplete = #ActionComplete,
tsa.CompleteDate = GETDATE(),
tsa.Notes = #ActionNotes
FROM blahblah
WHERE blahblah
But for what ever reason, the ASP.net parser inside the SqlDataSource control could not make sense of it (even though it ran perfectly inside the GUI's Test Query feature!).
I was getting
invalid object name in 'tsa'
So I placed the lot inside a Stored Procedure...
USE [mydatabase];
GO
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
ALTER PROCEDURE [dbo].[spTETupdateActions]
#StudentID VARCHAR(10),
#ActionComplete INT = 0,
#ActionNotes VARCHAR(MAX),
#TETmeetingID INT,
#WeekNo INT,
#TETID INT,
#TETdate DATETIME,
#ActionItem VARCHAR(MAX)
WITH
EXEC AS CALLER AS
UPDATE tsa
SET tsa.ActionComplete = #ActionComplete,
tsa.CompleteDate = GETDATE(),
tsa.Notes = #ActionNotes
FROM blahblah
WHERE blahblah
GO
And voila! No more errors! Why? Because the parsing of the SQL is done inside SQL Server not ASP.net!
Related
I have a stored procedure in a myscript.sql file that looks like this:
CREATE PROCEDURE [dbo].[_GetUserID]
#EmailAddress NVARCHAR(254)
AS
DECLARE #UserID UNIQUEIDENTIFIER;
SELECT #UserID = [ID]
FROM [dbo].[User]
WHERE [EmailAddress] = #EmailAddress
PRINT #UserID
GO
I have some C# code that relies on Dapper to run this script. I can successfully run this script when I copy-and-paste it into Azure Data Studio. However, when I am trying to run this script from code, I get an error:
Incorrect syntax near 'GO'
My C# code looks like this:
try
{
var script = File.ReadAllText("<path to myScript.sql is here>");
using (var connection = new SqlConnection(dbConnectionString))
{
var command = connection.CreateCommand();
command.CommandText = script;
command.CommandType = CommandType.Text;
connection.Open();
command.ExecuteNonQuery();
}
Console.WriteLine("Success.");
}
catch (Exception ex)
{
Console.WriteLine($"Failed. Reason: '{ex.Message}')");
}
I don't understand why I can run myScript.sql from Azure Data Studio, however, it's not working from my C# code. I'm also creating tables using the same approach and it works fine. I'm not sure what I'm missing.
GO is not a valid T-SQL keyword - it's a separator that is used by SQL Server Management Studio and obviously also Azure Data Studio.
To fix this, just simply remove that GO line from your .sql script file and run it without this - should be just fine.
On a different note: having nothing but a PRINT statement in your stored procedure doesn't make a lot of sense - don't you want to actually SELECT #UserId to get that data sent back to the caller??
Assume we have a stored procedure like so
CREATE PROCEDURE CopyValue(IN src INT, OUT dest INT)
BEGIN
SET dest = src;
END
I want to call this from a .net app (assume connection etc created successfully)
var sql = "call CopyValue(100, #destValue); select #destValue as Results;";
The string in the above statement works perfectly well when called in MySql Workbench.
However this - obviously - fails with "MySqlException: Parameter '#destValue' must be defined" when executed on a MySqlCommand object in .net
How do I arrange this statement so I can capture an output parameter from an existing procedure?
NB: I'm running against MySql 5.6, which I can't upgrade at this time.
NB Calling the procedure directly with CommandType.StoredProcedure goes against company guidelines.
By default, user-defined variables aren't allowed in SQL statements by MySQL Connector/NET. You can relax this restriction by adding AllowUserVariables=true; to your connection string. No modifications to your SQL or how you're executing the MySqlCommand should be necessary.
For information about why this is the default, you can read the research on this MySqlConnector issue (which also has the same default behaviour, but a much better error message that will tell you how to solve the problem): https://github.com/mysql-net/MySqlConnector/issues/194
A colleague (who wishes to remain anonymous) has answered this perfectly. Essentially put backticks ` after the # and at the end of the variable name e.g.
#`MyParam`
A fully working example.
static void Main(string[] args)
{
using var con = new MySql.Data.MySqlClient.MySqlConnection("Data Source=localhost; User Id=...;Password=...;Initial Catalog=...");
con.Open();
using var cmd = con.CreateCommand();
cmd.CommandText = "call CopyValue2(100, #`v2`); select #`v2` as Results;";
using var reader = cmd.ExecuteReader();
if (reader.Read())
Console.WriteLine($"Copied Value {reader.GetInt64(0)}");
}
Thanks OG :)
In my database, I have 2 schemas: [dbo] and [rch] ([rch] was selected as the name for our "archived" data so that those tables would not appear before the [dbo] tables).
I created a user for this table called rchuser in SQL Server Management Studio (SSMS):
Notice above that the user is added with rch listed as the Default Schema.
Notice above that this new user owns both db_owner and rch.
Let's say I have this SQL insert:
public static int AddRecord(object value, string sqlConnection)
{
int result = 0;
using (var conn = new System.Data.SqlClient.SqlConnection(sqlConnection))
{
conn.Open();
var sqlCmd =
"INSERT INTO Table1 ([Value], [Stamp]) " +
"VALUES (#Value, GETDATE()); ";
using (var cmd = new System.Data.SqlClient.SqlCommand(sqlCmd, conn))
{
cmd.Parameters.AddWithValue("#Value", value);
result = cmd.ExecuteNonQuery();
}
}
return result;
}
I passed that method a connection string using my rchuser credentials.
var conn = "Data Source=localhost;Initial Catalog=DatabaseN;User Id=rchuser;Password=password;"
There is no error, result is 1, but the new record is NOT in the corresponding table for my [rch] schema.
It is like the database is completely ignoring the fact that this user defaults to the [rch] schema.
I even tried logging into the SSMS database with rchuser to execute the command by hand. Again, no errors. The data went into [dbo].
How do I direct all database input to go to another schema?
If you have multiple schemas in a database, then my recommendation is to always explicitly specify which one you want. Aaron Bertrand has a good article on why you should do it, even if you only have one schema.
So modify your sql statement to be
INSERT INTO [rch].Table1...
and you will be all good.
I do note that this doesn't answer your title, but it does answer your question.
As to why your query isn't defaulting to the [rch] schema, I don't know. I replicated your setup in SQL Server 2008 R2, and when I run your original query then the inserts do go into the rch table as expected.
EDIT:
I did some Googling, and I suspect that your problem is caused by granting the sysadmin server role to the rchuser login. I modified mine to be an sa
, and now the inserts go into the [dbo] schema by default, even though rchuser has a default schema of [rch].
So, if you remove the sysadmin server role, it should start working as expected.
Have You tried to specifiy schema for table in Your query?
var sqlCmd =
"INSERT INTO rch.Table1 ([Value], [Stamp]) " +
"VALUES (#Value, GETDATE()); ";
My issue is that I have created a table for a local db in Visual Studio 10.0 using C# and I want to have an auto-incrementing field which I have setup. The table is created and the identity field seems to be setup correctly and everything seems fine, but I always get a syntax error on the insert when I use an identity field -- so I imagine I have a stupid little typo, but perhaps this is just not supported using VS?
This is the create table string and execution:
-connection string omitted-
string createTableString = #"CREATE TABLE [Test](
[Test_ID] [int] IDENTITY (1,1) PRIMARY KEY NOT NULL,
[OtherField] [varchar] (50))";
SqlCommand command = new SqlCommand(createTableString, con);
command.ExecuteNonQuery();
And this is what I'm using to insert into the table:
string insertString = #"INSERT INTO Test VALUES ('sometext')";
SqlCommand command1 = new SqlCommand(insertString, con);
command1.ExecuteNonQuery();
Note that I've tried this as well and get the same syntax error:
string insertString = #"INSERT INTO Test (OtherField) VALUES ('sometext')";
SqlCommand command1 = new SqlCommand(insertString, con);
command1.ExecuteNonQuery();
Also note that for this project I must do this via these scripting commands in Visual Studio. Is this possible? Thanks very much ahead of time.
The scripts look correct, I can only assume it has to do with the owner of the table. SQL makes the current user the owner of the table. Try [youruser].[Test] and see if that helps.
Possible test is the SQL keyword, try to add brackets around it: [test].
I am building a query using ODBC command object in .Net with multiple parameters being passed in. When executing the query against SQL Anywhere, I get the following error. (The same code works against SQL Server).
[System.Data.Odbc.OdbcException] = {"ERROR [07002] [Sybase][ODBC Driver][SQL Anywhere]Not enough values for host variables"}
The command object has the same number of parameters added as the place holders ('?') in the query. Following is a simple query and C# code that fails the test.
C# code to populate the host variables
String queryText= #"DECLARE #loanuseraddress varchar(40), #loanid decimal
Set #loanid = ?
Set #loanuseraddress = ?
select * from loan_assignments where loan_id = #loanid"
OdbcConnection connection = new OdbcConnection(request.ConnectionString);
OdbcCommand command;
command = new OdbcCommand(queryText, connection);
OdbcParameter param1 = new OdbcParameter("#loanid", OdbcType.Decimal);
param1.Value = request.Loan.LoanNumber;
command.Parameters.Add(param1);
OdbcParameter param2 = new OdbcParameter("#loanuseremployer", dbcType.VarChar);
param2.Value = appraisalCompanyUpdate.LoanUserEmployer;
if (param2.Value == null)
param2.Value = DBNull.Value;
command.Parameters.Add(param2);
connection.Open();
OdbcDataReader rows = command.ExecuteReader();
I fixed this by checking for nulls. When you try to pass a null parameter to Sybase, that's the error you get (at least for me). Have a feeling LoanId is null at some point.
Edit After doing a little more research, I think you can also get this error when you try multiple insert / deletes / updates through the Sybase ODBC Connection in .Net. I don't think this is supported and MSDN seems to say it's vendor specific.
"Insufficient host variables" can also mean something else but it's applicable to the OP:
one of the other causes could be that you have a set of declared variables different from the set your SQL statement is using.
E.g. this could be a typo, or you could have copied in SQL from Visual Studio that was used to fill a dataset table using parameters (like :parm) but in doing so you forgot to declare it (as #parm) in your stored proc or begin/end block.