SQL Command Name is Database Name; Use Dynamic SQL? - sql

I have a database with the name "Union". I am trying execute SQL for this database in the MAINT table but since 'union' is a SQL command it is throwing errors. I can get the query to run when executing from Union database. Would dynamic SQL be able to fix my problem or should I change the database name?
I keep getting incorrect syntax near keyword 'UNION' here is what I have so far,
DECLARE #sql varchar(max)
DECLARE #Database varchar(5)
Set #Database = 'UNION'
SELECT #sql = 'SELECT '+#Database+' as ''Database'', '+#Database+'.hsi.useraccount.username as ''User Name'',
'+#Database+'.hsi.useraccount.realname as ''Real Name''
FROM '+#Database+'.hsi.useraccount
WHERE '+#Database+'.hsi.useraccount.username NOT LIKE ''%deactivated%'' and '+#Database+'.hsi.useraccount.username not like ''%administrator'' and '+#Database+'.hsi.useraccount.username not like ''%internal%'''
execute(#sql)

Add [] brackets around Schema names.
SELECT #sql = REPLACE('SELECT [#Database] as ''Database'', [#Database].hsi.useraccount.username as ''User Name'',
[#Database].hsi.useraccount.realname as ''Real Name''
FROM [#Database].hsi.useraccount
WHERE [#Database].hsi.useraccount.username NOT LIKE ''%deactivated%'' and [#Database].hsi.useraccount.username not like ''%administrator'' and [#Database].hsi.useraccount.username not like ''%internal%'''
,'#Database',#Database)
As long as the text "#Database" text doesn't appear anywhere else in your select statement, just throw it into a REPLACE() function and avoid all that embedded quote syntax and string concatenation headache.

You also can use quotename instead of manually entering square brackets
declare #db nvarchar(100)
set #db='performance'
declare #sql nvarchar(max)
set #sql='select * from '+QUOTENAME(#db)+'.'+quotename('dbo')+'.'+QUOTENAME('orders')
print #sql
exec(#sql)

Related

Avoid using dynamic from clause

How can i avoid using dynamic from clause? Even if i don't know the database name, i prefer to use a static statement, like this:
select *
into #tempTable
from #DBName.Invoices
where InvoiceId = 5.
I got this error: Msg 102, Level 15, State 1, Line 6
Incorrect syntax near '.'.
I need to use select into clause because the column names may be different from each databases;
Thanks!
Unfortunately you will have to use dynamic SQL for this, see below for an example
Declare #DBNAME NVARCHAR(MAX) = 'xxx'
Declare #SQL NVARCHAR(MAX) ='select *
into #tempTable
from ' + #DBName + '.Invoices
where InvoiceId = 5.'
execute sp_executesql #SQL
How can i avoid using dynamic from clause? Even if i don't know the database name, i prefer to use a static statement
SQL wont accept columnnames,tablenames,databasenames as parameters.so unless you you avoid them,you cant avoid dynamic sql..
Change your query to dynamic sql to avoid error..But again you will have a problem with temp tables scope
--This will fail ,because temp table falls under different scope
Declare #sql nvarchar(4000)
set #sql='
select *
into #tempTable
from #DBName.Invoices
where InvoiceId = 5'
---one option is to use global temp tables
declare #dbname varchar(1000)
set #dbname=db_name()
declare #sql nvarchar(4000)
set #sql='select *
into ##tempTable
from '+#DBName+'.dbo.test_Delete '
exec(#sql)
select * from ##temptable
But be carefull with above approach,since above temp table have global scope..
You also can use Openrowset ,some thing like below
select * into #temp from openrowset
('SQLNCLI','Server=yourinstancename;Trusted_Connection=yes;', 'select * form table')

Using a variable to name query results column

Is there a way to use a variable to name a column in SQL query results? My example below gives an "Incorrect syntax" error?
declare #ColumnName varchar(100) = 'Column 1'
Select CustomerNumber as #ColumnName
from Customers
Generally, SQL isn't going to handle defining variables to use as column aliases. This means you'll likely have to resort to using dynamic SQL, which involves building your query and then executing it manually via the sp_executesql procedure.
The following is an example of your existing query executed dynamically using SQL Server :
-- Define your variable
DECLARE #ColumnName VARCHAR(100) = 'Column 1'
-- Define your SQL query
DECLARE #SQL NVARCHAR(200) = 'SELECT CustomerNumber AS ' + #ColumnName + ' FROM Customers'
-- Execute your query dynamically
EXEC sp_executesql #SQL

OPENQUERY(SERVERNAME, STOREDPROCEDURE) Syntax error

This is my code
DECLARE #stringvariable nvarchar(200) = 'Hello';
DECLARE #sql nvarchar(2000) = SELECT * INTO ##global FROM OPENQUERY(DB1, ''EXEC GETCASE ''' + #stringvariable + ''''')'
Printing #sql returns a correctly formatted query, however SQL Server doesn't like #stringvariable and returns an error
Msg 102, Level 15, State 1, Line 11
Incorrect syntax near 'Hello'.
Here is what the outputted query looks like
SELECT * INTO ##global FROM OPENQUERY(DB1, 'EXEC GETCASE 'Hello'')
How can I avoid this error? It seems like because my stored procedure takes a string parameter, it's throwing off the query. I've read that OPENQUERY does not support variables, but I've parameter the variable so it should work?
Appreciate your help!
The stored procedure exists in a database and a schema. You need to supply those. Supposing database db_name and schema schema_name:
DECLARE #stringvariable nvarchar(200) = 'Hello';
SET #stringvariable=REPLACE(#stringvariable,'''',''''''''''); -- doubly doubled single quotes for the dynamic statement
DECLARE #sql nvarchar(2000) = 'SELECT * INTO ##global FROM OPENQUERY(DB1, ''SET FMTONLY OFF;EXEC db_name.schema_name.GETCASE ''''' + #stringvariable + ''''''')';
I've also made sure single quotes are properly escaped in the #stringvariable.
It's also likely you need to start the query with SET FMTONLY OFF; so I've added that.
Update: To test this I created following simple procedure on a linked server local_server in database TEST_TT
CREATE PROCEDURE [dbo].[tst]
#i VARCHAR(128)
AS
SELECT #i AS field;
I then ran the following:
DECLARE #var VARCHAR(128)='TT.';
SET #var=REPLACE(#var,'''',''''''''''); -- doubly doubled single quotes for the dynamic statement
DECLARE #stmt VARCHAR(4000)='SELECT * INTO ##tt FROM OPENQUERY(local_server,''SET FMTONLY OFF;EXEC TEST_TT.dbo.tst '''''+#var+''''''');';
EXEC (#stmt);
SELECT * FROM ##tt;
DROP TABLE ##tt;
And I received the results. I count 7 (!!) single quotes at the end of the query... yuck! Updated original part with the same number of quotes.

SQL: SybaseDB and having parameterized variables in SELECT clauses

I am trying to create a stored procedure that selects from a database name that would be parameterized. However, I am having a lot of trouble doing so. I am trying to perform something as simple as the following:
DECLARE #tableName VARCHAR
SET #tableName = 'MY_TABLE_NAME'
SELECT
*
FROM
#tableName
This produces the error: Incorrect syntax near '#tableName'.
Could someone please tell me how I could select from a parameterized table name?
Execute dynamic SQL in this case.
DECLARE #tableName VARCHAR
SET #tableName = 'MY_TABLE_NAME'
exec('
SELECT
*
FROM ' + #tableName )

statement "USE #dbname" doesn't work, why? How to do that?

I've got this t-sql snippet:
DECLARE #db_name varchar(255);
SET #db_name = 'MY_DATABASE'; -- assuming there is database called 'my_database'
USE #db_name -- this line ends with error "Incorrect syntax near '#db'."
But USE with variable (third line of snippet) doesn't work.
Why it doesn't work?
You cannot provide the name of the database for USE statement in a variable.
As you have noticed, the USE statement does not accept a variable as parameter. The only alternative that quickly comes to mind is quite crude and extremely error prone, but here you go:
EXEC ('USE ' + #db_name + '
SELECT * FROM some_table
INSERT INTO some_table VALUES (1)')
I hope that someone else can do better :-)
SQL Server will not accept the USE statement with a variable.
To use database names dynamically, you have to create dynamic SQL statements with (almost) fully qualified names as follows:
Declare #SQL VarChar (100)
SET #SQL = 'SELECT * FROM ' + #DatabaseName + '.dbo.TableName'
and then you execute it using sp_SQLExec
The way I do this is with an if statement:
if #DBName = 'DB1'
<query with DB1>
else
<query with DB2>