SQL - select from variable - sql

I am trying to find an alternative to setting the content of a variable as a big query in which i'm dynamically replacing values.
Is it possible to do something like this?
declare #serv nvarchar(max)
set #serv = '[linkedServName].[dataBaseName]'
select top 10 * from #serv.dbo.someTable
If yes, could you please show me the correct syntax?
Thank you for your time

If you want to parameterize the server and database you select from, then you have to use dynamic sql. Try this:
declare #serv nvarchar(max)
declare #qry nvarchar(max)
set #serv = '[linkedServName].[dataBaseName]'
set #qry = 'select top 10 * from ' + #serv + '.dbo.someTable'
exec(#qry)

Related

Comparing table values with a variable SQL

I am trying to compare data from a table in SQL Server with a variable value, and I get the error
Must declare the scalar variable #DataSearched
This is my query:
DECLARE #DateSeached INT
SET #DateSeached = '9'
SELECT *
FROM Tax2ComputationType as t
INNER JOIN ComputationValue as c ON t.TaxId != c.ComputationTaxId
WHERE t.ValidityStartDate BETWEEN c.ValidityStartDate AND c.ValidityEndDate
AND t.ValidityEndDate > #DateSeached
I have also tried writing the code like this:
DECLARE #sql nvarchar(max)
SET #sql = 'SELECT * .....' and so on
SET #sql = #sql + 'AND t.ValidityEndDate >' + #DateSearched
And I get the same error. I searched for a time the answer and I couldn't find it. Can anyone help me?

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)

Specifying Column Name As A Parameter in SELECT statement?

I need to do something like this, but it always fails with 'Error converting data type varchar to int':
DECLARE #intParam INT
DECLARE #ColName VARCHAR(64)
SET #ColName='intcolumn'
SET #intParam = SELECT #ColName FROM myTable
How do I accomplish something like this? I can see the problem is that the SELECT statement simply returns the column name as a string, but I am not sure how to fix that. I am using SQL Server 2008R2.
You need to use dynamic sql:
build your dynamic SQL query (take a look at #SQL variable in sample below)
use output parameter to get value back from dynamic sql (take a look at #intParam and #intParam_out in sample below)
execute dynamic sql using sp_executesql
DECLARE #intParam INT
DECLARE #ColName VARCHAR(64)
SET #ColName='intcolumn'
DECLARE #SQL NVARCHAR(1000)
SET #SQL = 'SELECT #intParam_out = ' + #ColName + ' FROM myTable'
exec sp_executesql #SQL, N'#intParam_out int OUTPUT', #intParam_out = #intParam OUTPUT
Use Cast:
SET #intParam = SELECT cast(#ColName as int) FROM myTable

T-SQL creating a dynamic where statement?

I know this is not possible, but is there something that would work? Basically I want the where statement to be dynamic, allowing me to pass it any string, which it will be able to search upon.
Declare #search varchar(80)
set #search = 'RegionID'
Select * from TBL_TripDetails
Where #search = '1'
Thanks for your answers. After reading a few documents, I have decided to use multiple select statements instead of using dynamic sql. thanks!
declare #sql nvarchar(max);
set #sql = N'select * from table where ' + quotename(#search) + N'=''1''';
exec sp_executesql #sql;
See The Curse and Blessings of Dynamic SQL
It is indeed possible, altough is often frowned upon.
Have a look at sp_executesql
Declare #search varchar(80)
set #search = 'RegionID'
declare #query varchar(max)
set #query = "Select * from TBL_TripDetails Where " + #search + " = '1'"
exec #query
DECLARE #search VARCHAR(80)
DECLARE #SQL VARCHAR(8000)
SET #search = 'RegionID'
SET #SQL = 'SELECT * FROM TBL_TripDetails WHERE ' + #search + ' = 1'
EXEC #SQL
Be careful though. Concatenating SQL can allow SQL injection attacks.
I'm a bit confused with your question "pass it any string, which it will be able to search upon". In your example your passing in a field which is being compared against a hard coded value of 1, this doesn't really match your description.
If this is truly what you wanted, then you'll need to use Dynamic SQL. If you just want to be able to support optional search criteria/parameters (e.g. If RegionID has a value set then apply criteria, else ignore criteria), then use the example below.
DECLARE #RegionID AS VARCHAR(1);
SELECT *
FROM TABLE
WHERE (#RegionID Is Null OR #RegionID = '' OR RegionID = #RegionID);
Now, if #RegionID is blank or NULL it won't be used in the criteria.

Creating SQL table using dynamic variable name

I want to create backup SQL tables using variable names.
something along the lines of
DECLARE #SQLTable Varchar(20)
SET #SQLTable = 'SomeTableName' + ' ' + '20100526'
SELECT * INTO quotename(#SQLTable)
FROM SomeTableName
but i'm getting
Incorrect syntax near '#SQLTable'.
It's just part of a small script for maintence so i don't have to worry about injections.
DECLARE #MyTableName sysname;
DECLARE #DynamicSQL nvarchar(max);
SET #MyTableName = 'FooTable';
SET #DynamicSQL = N'SELECT * INTO ' + QUOTENAME(#MyTableName) + ' FROM BarTable';
EXEC sp_executesql #DynamicSQL;
Unfortunately, you can't use bind variables for table names, column names, etc. IN this case you must generate dynamic SQL and use exec.
DECLARE #Script NVARCHAR(MAX);
SET #Script = N'SELECT * INTO SomeTableName_' + N'20100526' + N' FROM SomeTableName';
EXEC sp_executesql #Script
I've left the date separate as I assume you want to calculate it for every run.
You should look into using synonyms:
-- Create a synonym for the Product table in AdventureWorks2008R2.
CREATE SYNONYM MyProduct
FOR AdventureWorks2008R2.Production.Product;
GO
-- Query the Product table by using the synonym.
USE tempdb;
GO
SELECT ProductID, Name
FROM MyProduct
WHERE ProductID < 5;
GO
http://msdn.microsoft.com/en-us/library/ms177544.aspx
DECLARE #MyTableName nvarchar(20);
DECLARE #DynamicSQL nvarchar(1000);
SET #MyTableName = "FooTable";
SET #DynamicSQL = N'SELECT * INTO ' + #MyTableName + ' FROM BarTable';
exec #DynamicSQL;
this query is correct but just use single quote at the ("FooTable")='FooTable'