Avoid using dynamic from clause - 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, 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')

Related

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 Command Name is Database Name; Use Dynamic 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)

SQL SELECT results INTO temp table using query string

I am trying to write some dynamic SQL queries that select results into a temp table with a query string. It looks like follows:
DECLARE #SQL Varchar(4000)
SET #SQL = 'SELECT * INTO #tmp_tab FROM dbo.sometable'
EXEC(#SQL)
It doesn't give any error to run the code, but when I want to select from #tmp_tab, it says the table doesn't exist.
So I am wondering if there is any special syntax for it, or dynamic SQL doesn't support such operation?
Many thanks.
Maybe it has something to do with access. If you create a global temp table, it will work.
DECLARE #SQL Varchar(4000)
SET #SQL = 'SELECT * INTO ##tmp_tab FROM dbo.batch'
EXEC(#SQL)
SELECT * FROM ##tmp_tab

How to access a database given a string of its name

Alright so say I have code that looks like this.
CREATE Table database_info
(
DBName NVARCHAR (MAX)
);
INSERT INTO database_info (DBName)
VALUES ('db1')
SELECT * FROM database_info
DECLARE #temp nvarchar(MAX)
SET #temp = (SELECT DBName FROM database_info where database_info.DBName = 'db1')
--How I want it to work SELECT * FROM #temp
Is there any kind of operation I could do on this temporary variable to have the string act as a regular SQL command?
Thanks
You may execute a dynamic sql using EXEC. Now, declaring the #sql variable would be quite too much in this case, but it is useful when you are not sure of the length of the statement you will pass to it.
DECLARE #sql AS VARCHAR(MAX)
SET #sql = 'SELECT * FROM ' + #temp
EXEC(#sql)

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 )