Can I execute SQL with parameters from within Visual Studio? - sql-server

EDIT: Judging from the comments, I have been unclear in what I am trying to achieve. I'll try from another angle.
I have been developing sprocs for a number of years. I increasingly feel that choosing between SQL embedded in C# code and sprocs are both bad choices. I know that many people will disagree and that's fine.
I didn't elaborate on this in the question to avoid having the discussion be about sprocs or not :-) .
As an experiment, I have tried embedding .sql files in my project in Visual Studio. Literally, in my project tree I have files with the .sql extension and the Build Action set to Embedded Resource.
That way I can edit the SQL query code from within VS and even run/execute it from within VS, without running the project. I love that. The actual code that I am working on right now, is akin to a "product list" with paging and multiple ordering and filtering options. The SQL query has parameters like #skip, #search, etc. This means that if I try to run/execute it from within VS (specifically by pressing CTRL + SHIFT + e or selecting "Execute" from the "SQL" menu in VS) these parameters are missing (of course), since they are meant to be provided as SqlParameter at runtime. I understand why this happens and by no way intend to imply that either VS or SSMS is bugged. I am merely looking for a way to "tell" VS that "When I execute this query from within VS, I intend for #skip to be 10". I (perhaps mistakenly) assumed that the reason that VS had IntelliSense support and Execute support for .sql files was to support a scenario akin to what I am trying).
I was just hoping someone else was doing the same and had a clever way/addon/trick to support it.
EDIT END
In an project in Visual Studio 2017, I have a number of .sql files which are embedded into the application when built.
While editing the files in VS, I can conveniently connect to a SQL server and execute the query.
However, if the query has parameters like this:
SELECT * FROM Employee WHERE ID=#ID;
The execution, from within Visual Studio, fails with
Must declare the scalar variable "#ID".
This can be "fixed" by adding a line at the top of the script/file, so it looks like:
DECLARE #ID int = 123;
SELECT * FROM Employee WHERE ID=#ID;
However, now it doesn't work when called from within the code like this (using Dapper, it's not relevant to the question, but explains the syntax):
var emp = conn.Query<Employee>( sql, new { ID=123 } );
I was hoping that either I could specify the value of ID somewhere not in the file, or specify some part of the file which VS would execute, but would be ignored later when calling from code.
EDIT: To be clear, I can craft the SQL so that it works flawlessly from within Visual Studio or at runtime, but I cannot have both. I was hoping there was some neat hack, a VS addon or just some VS feature that I was just missing. I have considered adding a simple pre-processor so I can do something like this:
--if DEBUG
DECLARE #ID int = 123;
--endif
SELECT * FROM Employee WHERE ID=#ID;
And then I could add it to my function that loads the embedded resource.

Pardon if I understood the question wrongly. Could it be you're looking for something like this? The query approach actually doesn't matter, it more looks like the issue is that you declare it like #ID when you actually have to add the replacement to the script itself
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT * FROM Employee WHERE ID=#ID;";
cmd.Parameters.Add("#ID", actualID); <--this is is why declaring doesn't work - You can declare it, but you also need to add it to the query
SqlDataReader rdr = cmd.ExecuteReader();

Five years have passed since the original post remains without the answer, and now I stumbled upon it because I am trying to do exactly the same as Thomas.
One way to do it, which is far from perfect, is to add the parameters with test values in the SQL file on top of the query. (e.g. DECLARE #p1=10) Later they need to be removed of course.
What is needed in my view in VS is a user interface like when a stored procedure with parameters is run from SQL Server Management studio and it pops up with a form where parameters can be set before the SP runs.

Related

What is the ProgressDB equivalent to SQL Server's statement Select ID = '1'?

When attempting to use a query I wrote against a Progress DB, I assumed I could use the following statement:
SELECT ID = '1' FROM Table
That returns a syntax error, but it's perfectly normal syntax for SQL Server.
Rule #1 -- Progress is not SQL. The more you try to make it act like SQL the unhappier you will be.
There is a SQL-92 interface. Naturally it does not support much in the way of syntax specific to Microsoft or Oracle. "Perfectly normal for MS SQL Server" is no assurance that Progress will think it normal.
There is an older still SQL-89 embedded within the 4GL engine. This is even less likely to behave like MS SQL.
Of course a great deal depends on which of these engines you are using and what version of Progress you are working with.
Having said that -- you have no table name. I'm just a Progress guy and maybe that's some sort of fancy-pants MS SQL magic or a code snippet from the midst of something more interesting but that looks like a problem to me. I would have been coding something more like:
SELECT name FROM customer WHERE id = 1

An example of the file structure dbf

I have a short example on how to generate dbf files like
I saw the following link:
Data File Header Structure for the dBASE Version 7 Table File
I write my program with C #
For example, I want to produce the following table( to binary ):
Field Name Type MaxLength
-------------------------------------------
DSK_ID Character 100
DSK_ADRS Numeric 2
Are you trying to create the table within Foxpro (Visual Foxpro) itself?, DBase, or with a .net/java language. Your tabs are unclear as to what you are really getting into, and just creating the table via low-level is not the way to go.
I can modify this answer more, but suggest you edit your question to provide more detail.
The basic syntax, if using Visual FoxPro would be something like.
create table SomeTableName ( DSK_ID C(100), DSK_ADRS N(2,0) )
But again, would need more on the environment you plan on working with.
By knowing you want to do via C#, I would start by Downloading Microsoft's VFP OleDb provider.
Then, you can look at the many other links for connecting, querying (always parameterize) and execute what you need. Here is a short example to get a connection and create the table you want. Then it is up to you for querying, inserting, updating as needed.
OleDbConnection oConn = new OleDbConnection("Provider=VFPOLEDB.1;Data Source=C:\\SomePath");
OleDbCommand oCmd = new OleDbCommand();
oCmd.Connection = oConn;
oCmd.Connection.Open();
oCmd.CommandText = "create table SomeTableName ( DSK_ID C(100), DSK_ADRS N(2,0) )";
oCmd.ExecuteNonQuery();
oConn.Close();
Now, note, the "Connection" string has a Data Source. This should point to a PATH location where you WANT TO CREATE and/or QUERY the tables. You can have one connection that points to a folder that has 100+ tables and you can eventually query from any of them. But again, those are going to be other questions that you can find LOTS of answer to for sampling... for example, just search on
VFP OleDB C# and you will get plenty of hits
How are you going to handle memo files? Compound index files?
Just use the ODBC or Ole DB providers via COM InterOp and issue a CREATE TABLE.

See contents of table variable using immediate / locals windows

In SSMS and its immediate or locals window, is there a way to see the contents of table variable?
I can select and view the value of scalars, but I can't seem to find a way to query the contents of tables or even run
SELECT * FROM #someTableVarInMySproc
in the immediate window. Is there any way to do this?
No, sorry, this is not possible in current versions of Management Studio. It has been asked for, and it's been stated that they are considering something similar in a future version. You can vote and add constructive comments on the following items, though there is no guarantee they'll ever actually do it:
http://connect.microsoft.com/SQL/feedback/details/623353
http://connect.microsoft.com/SQL/feedback/details/582167
http://connect.microsoft.com/SQL/feedback/details/454870
http://connect.microsoft.com/SQL/feedback/details/363054
The first item in that list has an interesting workaround:
In addition to the obvious caveat that you may not be able to inject additional code to capture the data in an XML variable (because after all, if you can do this, you could also add old-school debugging techniques like SELECT * FROM #table), and the cumbersome nature of trying to read this information from XML, Management Studio 2012 crashed on me the first time I tried to do this - so if you're going to try it, make sure you do so in an isolated instance.

How can I get the # of rows affected by a statement using ADO with JavaScript?

I'm using ADO in a JScript (Microsoft JavaScript dialect) Windows Scripting Host script to update a SQL Server table. I'd like to get the number of rows affected by the update in the script, but JavaScript doesn't have pass-by-reference and so I can't do the usual thing where I receive the records affected from the Command#Execute function's RecordsAffected argument. So I'm looking for the best way to get that info.
For reasons not related directly to this query, I want to avoid using a stored procedure for this although I realize that that would work (I'd just return ##rowcount out of the SP). I'm trying to find a reliable but simple non-SP means of doing it.
I looked around and found this syntax for the statement:
UPDATE MyTable
SET MyColumn = (blah blah blah)
WHERE (blah blah blah) ;
SELECT ##rowcount as 'RowsAffected'
...which sends me back a one-row ResultSet containing the count. That does seem to work, and in my limited testing seems to work correctly (I don't get the wrong count when other operations are also happening, etc.), but it seems...kludgy for some reason.
Is that the best way to do it, given the perhaps-unreasonable constraints I've listed? Cross-platform solutions are not required (welcome, though, as always), it can be Microsoft SQL Server-specific (2005+).
Thanks in advance.
Not sure why you think it's kludgy. Nothing wrong with this approach.

How can I stop SQL Server Management Studio replacing 'SELECT *' with the column list?

SQL Server Mgmt Studio is driving me crazy.
If I create a view and SELECT '*' from a table, it's all OK and I can save the view.
Looking at the SQL for the view (eg.by scripting a CREATE) reveals that the 'SELECT *' really is saved to the view's SQL.
But as soon as I reopen the view using the GUI (right click > modify), SELECT * is replaced with a column list of all the columns in the table.
How can I stop Management Studio from doing this ? I want my 'SELECT *' to remain just that.
Perhaps it's just the difficulty of googling 'SELECT *' that prevented me from finding anything remotely relevant to this (i did put it in double quotes).
Please, I am highly experienced in Transact-SQL, so please DON'T give me a lecture on why I shouldn't be using SELECT *. I know all the pros and cons and I do use it at times. It's a language feature, and like all language features can be used for good or evil (I emphatically do NOT agree that it is never appropriate to use it).
Edit: I'm giving Marc the answer, since it seems it is not possible to turn this behaviour off. Problem is considered closed. I note that Enterprise Manager did no similar thing.
The workaround is to either edit SQL as text, or go to a product other than Managment Studio. Or constantly edit out the column list and replace the * every time you edit a view. Sigh.
When SQL Server Mgmt Studio creates a view, I assume they're expanding the * to the complete list of columns that are present in the underlying table(s) at that particular time exactly for this reason: what if one of the underlying tables changes? Do you want the new columns to just simply show up in every view that references that table?? Seriously???
I think Microsoft tries to impmenent the "element of least surprise" here - your view will contain those columns that are present at the time the view gets created - and it stays that way, unless you explicitly and knowingly change that.
I for one wouldn't want to have my views suddenly having more columns than before, when an underlying table changes..... do you??
And I don't think there's any setting in Mgmt Studio to turn this behavior off, sorry.
Don't use the GUI editor.
Instead use the T-SQL editor. You get this by selecting "Script View As" -> "ALTER to" -> "New Query Window" from the right-click menu.
Try either of these: they are alternatives to using the GUI and can be setup as snippets with keyboard shortcuts:
select view_definition
from information_schema.views
where table_name = 'viewname'
or
exec sp_helptext 'viewname'
The results will retain the "select *". (Tested)

Resources