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)
Related
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')
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
I need to get the table name to query from a table.
var tableName = "select tableName from tableList where type='A';"
Then subsequently use that table name in another query.
"select * from" + tableName
Transact SQL/stored procedures are new to me in general so any help would be appreciated. I didn't design the database and unfortunately can't really change it to be a better design as much as I would love to!
My question is - is this possible from one stored procedure and if so can anyone mock up how I'd do it.
Or if there are any better ways anyone can think of (bar redesigning the database!)
Thanks
Maybe via dynamic SQL
DECLARE #String AS VARCHAR(8000)
DECLARE #TableName AS VARCHAR(50)
DECLARE #Results AS VARCHAR(8000)
SET #TableName = (select top 1 tableName from tableList where type='A')
SET #String = 'Select * from ' + #TableName
SET #Results = #String + #TableName
EXEC #Results
You can either use execas #kevchadders suggested or you can use sp_executesql, read The Curse and Blessings of Dynamic SQL for an excellent explantion on dynamic SQL.
You should use dynamic SQL to achieve that.
Basically, you execute your query using sp_executesql or exec, and store the result to a, kinda, staging table to be processed further:
declare #sql = varchar(8000);
select #sql = 'insert into resulttbl select * from ' + #tableName;
exec sp_executesql(#sql);
-- further process using resulttbl
Or
insert into resulttbl
exec ('select * from ' + #tableName);
-- further process using resulttbl
Anyway, you should read the following article for a better explanation: The Curse and Blessings of Dynamic SQL
You can directly write
select * from (select tableName from tableList where type='A') X
Greetings, I have a problem as follows:
I have an SQL variable declared:
DECLARE #myVariable nvarchar(max)
a third party library set a value for this variable. To simplify, lets say that the value is as follows:
SET #myVariable = 'Select ROWGUID from MySampleTable'
Now, I want to execute the following query:
SELECT ROWGUID FROM myTable WHERE ROWGUID in (exec sp_executesql #myVariable )
However, the above statement does not work because it returns an error telling me that I can't execute stored procedure in that way. I made a workaround and this is what I wrote:
create table #temptable (ID uniqueidentifier null)
if(#myVariable is not null AND #myVariable !='') insert into #temptable exec sp_executesql #myVariable
SELECT ROWGUID FROM myTable WHERE ROWGUID in (select * from #temptable)
DROP TABLE #temptable
This works fine.However I don't think it is a good idea to use temporary table. How can I achieve the same result without necessity of creating temporary tables?
I am using SQL SERVER 2005
UPDATE
Please read what I've written where is the problem:
However, the above statement does not work because it returns an error telling me that I can't execute stored procedure in that way. I made a workaround and this is what I wrote:
Keep it simple
-- Your original declaration
declare #myVariable nvarchar(max)
set #myVariable = 'Select ROWGUID from MySampleTable'
-- Additional code
declare #myQuery nvarchar(max) = 'SELECT ROWGUID FROM myTable WHERE ROWGUID in (' + #myVariable + ')'
exec (#myQuery)
Maybe you could use User Defined Functions instead of stored procedures?
If you are using SQL Server 2005 or 2008, you could use a Common Table Expression instead of creating a temporary table.
Common Table Expressions
Your CTE should look like:
WITH Records (ROWGUID) AS (
SELECT ROWGUID
FROM MySimpleTable
)
Then you can simply use:
SELECT ROWGUID
FROM myTable
WHERE ROWGUID IN (SELECT ROWGUID
FROM Records);
Which potentially means you can drop your Variable.
EDIT
Ok, so CTE is out of the question. But, what about using a Table variable instead of creating a Temporary Table.
DECLARE #myVar nvarchar(max);
DECLARE #table TABLE
(
ROWGUID uniqueidentifier
)
SET #myVar = 'SELECT ROWGUID FROM MySampleTable';
INSERT INTO #table
EXEC sp_executesql #myVar;
SELECT ClientID
FROM myTable
WHERE EXISTS (SELECT ClientID FROM #table);
I have some code like this that I use to do a BULK INSERT of a data file into a table, where the data file and table name are variables:
DECLARE #sql AS NVARCHAR(1000)
SET #sql = 'BULK INSERT ' + #tableName + ' FROM ''' + #filename + ''' WITH (CODEPAGE=''ACP'', FIELDTERMINATOR=''|'')'
EXEC (#sql)
The works fine for standard tables, but now I need to do the same sort of thing to load data into a temporary table (for example, #MyTable). But when I try this, I get the error:
Invalid Object Name: #MyTable
I think the problem is due to the fact that the BULK INSERT statement is constructed on the fly and then executed using EXEC, and that #MyTable is not accessible in the context of the EXEC call.
The reason that I need to construct the BULK INSERT statement like this is that I need to insert the filename into the statement, and this seems to be the only way to do that. So, it seems that I can either have a variable filename, or use a temporary table, but not both.
Is there another way of achieving this - perhaps by using OPENROWSET(BULK...)?
UPDATE:
OK, so what I'm hearing is that BULK INSERT & temporary tables are not going to work for me. Thanks for the suggestions, but moving more of my code into the dynamic SQL part is not practical in my case.
Having tried OPENROWSET(BULK...), it seems that that suffers from the same problem, i.e. it cannot deal with a variable filename, and I'd need to construct the SQL statement dynamically as before (and thus not be able to access the temp table).
So, that leaves me with only one option which is to use a non-temp table and achieve process isolation in a different way (by ensuring that only one process can be using the tables at any one time - I can think of several ways to do that).
It's annoying. It would have been much more convenient to do it the way I originally intended. Just one of those things that should be trivial, but ends up eating a whole day of your time...
You could always construct the #temp table in dynamic SQL. For example, right now I guess you have been trying:
CREATE TABLE #tmp(a INT, b INT, c INT);
DECLARE #sql NVARCHAR(1000);
SET #sql = N'BULK INSERT #tmp ...' + #variables;
EXEC master.sys.sp_executesql #sql;
SELECT * FROM #tmp;
This makes it tougher to maintain (readability) but gets by the scoping issue:
DECLARE #sql NVARCHAR(MAX);
SET #sql = N'CREATE TABLE #tmp(a INT, b INT, c INT);
BULK INSERT #tmp ...' + #variables + ';
SELECT * FROM #tmp;';
EXEC master.sys.sp_executesql #sql;
EDIT 2011-01-12
In light of how my almost 2-year old answer was suddenly deemed incomplete and unacceptable, by someone whose answer was also incomplete, how about:
CREATE TABLE #outer(a INT, b INT, c INT);
DECLARE #sql NVARCHAR(MAX);
SET #sql = N'SET NOCOUNT ON;
CREATE TABLE #inner(a INT, b INT, c INT);
BULK INSERT #inner ...' + #variables + ';
SELECT * FROM #inner;';
INSERT #outer EXEC master.sys.sp_executesql #sql;
It is possible to do everything you want. Aaron's answer was not quite complete.
His approach is correct, up to creating the temporary table in the inner query. Then, you need to insert the results into a table in the outer query.
The following code snippet grabs the first line of a file and inserts it into the table #Lines:
declare #fieldsep char(1) = ',';
declare #recordsep char(1) = char(10);
declare #Lines table (
line varchar(8000)
);
declare #sql varchar(8000) = '
create table #tmp (
line varchar(8000)
);
bulk insert #tmp
from '''+#filename+'''
with (FirstRow = 1, FieldTerminator = '''+#fieldsep+''', RowTerminator = '''+#recordsep+''');
select * from #tmp';
insert into #Lines
exec(#sql);
select * from #lines
Sorry to dig up an old question but in case someone stumbles onto this thread and wants a quicker solution.
Bulk inserting a unknown width file with \n row terminators into a temp table that is created outside of the EXEC statement.
DECLARE #SQL VARCHAR(8000)
IF OBJECT_ID('TempDB..#BulkInsert') IS NOT NULL
BEGIN
DROP TABLE #BulkInsert
END
CREATE TABLE #BulkInsert
(
Line VARCHAR(MAX)
)
SET #SQL = 'BULK INSERT #BulkInser FROM ''##FILEPATH##'' WITH (ROWTERMINATOR = ''\n'')'
EXEC (#SQL)
SELECT * FROM #BulkInsert
Further support that dynamic SQL within an EXEC statement has access to temp tables outside of the EXEC statement. http://sqlfiddle.com/#!3/d41d8/19343
DECLARE #SQL VARCHAR(8000)
IF OBJECT_ID('TempDB..#BulkInsert') IS NOT NULL
BEGIN
DROP TABLE #BulkInsert
END
CREATE TABLE #BulkInsert
(
Line VARCHAR(MAX)
)
INSERT INTO #BulkInsert
(
Line
)
SELECT 1
UNION SELECT 2
UNION SELECT 3
SET #SQL = 'SELECT * FROM #BulkInsert'
EXEC (#SQL)
Further support, written for MSSQL2000 http://technet.microsoft.com/en-us/library/aa175921(v=sql.80).aspx
Example at the bottom of the link
DECLARE #cmd VARCHAR(1000), #ExecError INT
CREATE TABLE #ErrFile (ExecError INT)
SET #cmd = 'EXEC GetTableCount ' +
'''pubs.dbo.authors''' +
'INSERT #ErrFile VALUES(##ERROR)'
EXEC(#cmd)
SET #ExecError = (SELECT * FROM #ErrFile)
SELECT #ExecError AS '##ERROR'
http://msdn.microsoft.com/en-us/library/ms191503.aspx
i would advice to create table with unique name before bulk inserting.