Using variables inline SQL ( MSSQL ) - sql

Possible to do something like this... MSSQL ?
where the #myText variable equals a string of 'id = 5'
SELECT * FROM someTable WHERE ( #myText )

Thanks guys. With your help led me to using temporary tables like so....
DECLARE #companies TABLE (comp_code INT) -- create temporary table
INSERT INTO #companies VALUES (5) -- ( repeat this line for each additional company you wish to keep )
DELETE FROM tableOne Where (Comp_Code NOT IN (select comp_code from #companies));
DELETE FROM tableTwo Where (Comp_Code NOT IN (select comp_code from #companies));
DELETE FROM tableThree Where (Comp_Code NOT IN (select comp_code from #companies));
-- etc etc

You need to use dynamic SQL. In SQL Server, this looks like:
declare #sql nvarchar(max);
set #sql = 'SELECT * FROM someTable WHERE ([myText])';
set #SQL = replace(#sql, '[mytext]', #mytext);
exec sp_executesql #sql;

Related

Cross-database subquery on using database name stored in record

Is the script structure below possible?
Select
*,
(Select Count(*)
from [A.DatabaseName].dbo.TableA
where SomeID = A.SomeID) As Total
From
[Database1].dbo.Table1 A
The subquery above is dependent on the database name from [Database1].
Is this doable? If yes, how can this be implemented?
The Dynamic Query will help you.
DECLARE #DBName VARCHAR(100),#SQLQuery VARCHAR(1000)
SELECT #DBName = A.DatabaseName FROM [Database1].dbo.Table1
SELECT #SQLQuery = 'Select
*,
(Select Count(*)
from '+#DBName+'.dbo.TableA
where SomeID = A.SomeID) As Total
From
[Database1].dbo.Table1 A'
EXEC (#SQLQuery)
---> Edit
I think i understand the weird thing you are tying to do.
You store some database name into a table and the want to call if from a subquery.
You have to try something like this :
CREATE DATABASE test
use test
CREATE TABLE client
(
ID IDENTITY(1,1),
[name] varchar(20)
)
INSERT INTO client
([name])
VALUES
('Jean'), ('Paul'), ('Mark'), ('Pierre');
CREATE TABLE allTable
(
NomSchema VARCHAR(200),
NomTable VARCHAR(200)
)
INSERT INTO allTable
VALUES
(
'TEST','client'
)
IF OBJECT_ID('tempdb..#ResultA') IS NOT NULL
DROP TABLE #ResultA
BEGIN TRAN
DECLARE #sql VARCHAR(200);
SELECT TOP(1) * INTO #resultA FROM allTable
SET #sql = 'SELECT * FROM ' + (SELECT quotename(#resultA.NomSchema) + '.dbo.' + quotename(#resultA.NomTable) FROM #resultA)
SELECT #sql
EXEC(#sql)
DROP TABLE #resultA
COMMIT
GO
-- DROP DATABASE TEST

SQL: Replacing part of query by subquery in FROM clause

I have a database including a table called [Table] which lists all tables in that database. Now I want to write a SQL query using some JOINS, which gets a specific tablename from [Table] in a subquery to select from that table... I hope this is not too confusing.
So [Table] looks like this:
IdTable Tablename
1 Adress
2 Project
3 User
...
The query should look like this:
SELECT * FROM (SELECT Type FROM dbo.[Table] WHERE tablename = 12)
Would something like that be possible?
I know, that subqueries are possible, but I do not know how to do that in this case.
Thanks in advance.
Regards
Lars
Try this below dynamic code to get your expected result.
DECLARE #sqlCommand AS NVARCHAR(MAX)
DECLARE #TableName AS NVARCHAR(MAX)
SELECT #TableName = tablename FROM dbo.[Table] WHERE Type = 12
SET #sqlCommand= N'SELECT * FROM '+#TableName+''
EXEC (#sqlCommand)
Note: I guess you wants to select TableName where Type = 12 and I alter the selection and filtering accordingly.
You can also execute the query directly as below without creating the command string-
DECLARE #TableName AS NVARCHAR(MAX)
SELECT #TableName = tablename FROM dbo.[Table] WHERE Type = 12
EXEC (N'SELECT * FROM '+#TableName+'')

If condition not working inside dynamic sql

In below dynamic sql I am trying to check whether temporary table (#Table) already exists if not then create using some other table.
But my problem is that irrespective what is the value in IF condtion, I am always getting error for select statement which is inside If condition
There is already an object named '#Table' in the database.
Below is the sql code.
declare #sqlstring varchar(max)
set #sqlstring=N'
select * into #Table from mst_country
if(object_id(''tempdb..#Table'') is null)
begin
select * into #Table from mst_country_bkp
end'
exec(#sqlstring)
Can any one please let us know why it can be happening?
You need to drop the temp table once you are done with your query like this:
declare #sqlstring varchar(max)
set #sqlstring=N'
IF OBJECT_ID(''tempdb.dbo.#Table'', ''U'') IS NOT NULL
DROP TABLE #Table;
select * into #Table from mst_country
if(object_id(''tempdb..#Table'') is null)
begin
select * into #Table from mst_country_bkp
end'
exec(#sqlstring)
EDIT:
The issue is that you cannot have two SELECT INTO inside the same sql statement. This is a leftover from SQL 6.5 which did not have deferred name resolution. Try this:
declare #sqlstring varchar(max)
set #sqlstring=N'
IF OBJECT_ID(''tempdb.dbo.#Table'', ''U'') IS NOT NULL
DROP TABLE #Table;
select * into #Table from mst_country
insert into #Table(col1,col2,....)
select col1,col2,.... from mst_country_bkp
end'
exec(#sqlstring)
When compiling the sqlserver doesn't allow you creating the same temporary table in the same scope twice. You can actually cheat the sqlserver like this, so it doesn't realize that the temporary table was already created:
declare #sqlstring varchar(max)
set #sqlstring=N'
exec(''select * into #Table from mst_country'')
if(object_id(''tempdb..#Table'') is null)
select * into #Table from mst_country_bkp
'
exec(#sqlstring)

How to iterate through each row in sql server?

My query returns 26 table names.
select name from sys.tables where name like '%JPro_VP_Service%'
Now I'm trying to write a query to check in every table return from the above query.
--consider this is my first table
select * from JPro_VP_Service
where row_id like '%1-101%' or row_id like '%1-102%'
-- likewise I want to search in 26 tables return from above query
I think I need to write for or cursor to accomplish this.
Can anyone help me how to achieve this?
The easiest way to do this is
Try this:
SELECT 'select * from ' + name
+ ' where row_id like ''%1-101%'' or row_id like ''%1-102%'''
FROM sys.tables
WHERE name LIKE '%JPro_VP_Service%'
you will get all tables together with the same conditions. You could execute them together.
Yes, you would have to use a cursor for this, and probably also dynamic sql
Also see
Generate dynamic SQL statements in SQL Server
Dynamic SQL PROs & CONs
DECLARE #mn INT
DECLARE #mx INT
DECLARE #tblname VARCHAR(100);
WITH cte
AS (SELECT Row_number()
OVER (
ORDER BY (SELECT 0)) AS rn,
name
FROM sys.tables
WHERE name LIKE '%JPro_VP_Service%')
SELECT #mn = Min(rn),
#mx = Max(rn)
FROM cte
WHILE( #mn >= #mx )
BEGIN
SELECT #tblname = name
FROM cte
WHERE rn = #mn
SELECT *
FROM #tblname
WHERE row_id LIKE '%1-101%'
OR row_id LIKE '%1-102%'
--Do something else
SET #mn=#mn + 1
END
This route may work, though you might want the results saved to a table:
DECLARE #tables TABLE(
ID INT IDENTITY(1,1),
Name VARCHAR(100)
)
INSERT INTO #tables (Name)
SELECT name
FROM sys.tables
WHERE name like '%JPro_VP_Service%'
DECLARE #b INT = 1, #m INT, #table VARCHAR(100), #cmd NVARCHAR(MAX)
SELECT #m = MAX(ID) FROM #tables
WHILE #b <= #m
BEGIN
SELECT #table = Name FROM #tables WHERE ID = #b
SET #cmd = 'select * from ' + #table + '
where row_id like ''%1-101%'' or row_id like ''%1-102%''
'
EXECUTE sp_executesql #cmd
SET #b = #b + 1
SET #cmd = ''
END

T-Sql getting data from tempdb table

I'm using Microsoft SQL Server 2008 R2 (RTM) - 10.50.1600.1 (X64) and I'm trying to make a SELECT statement to a table that have been created like this:
DECLARE #Sql AS VARCHAR(1500)
SET #Sql = 'SELECT 1 AS id, ''123'' AS value INTO #tmp_prueba'
EXECUTE ( #Sql )
SELECT * FROM #tmp_prueba
But I'm noticed that the table not exists
How can I get the data from the table?
The temporary table that you created in #sql is out-of-scope of the outer query.
Here is one way to do what you want:
DECLARE #Sql AS VARCHAR(1500);
SET #Sql = 'SELECT 1 AS id, ''123'' AS value INTO #tmp_prueba;
select * from #tmp_prueba'
create table #tmp_prueba (id int, value varchar(255));
insert into #tmp_prueba
EXECUTE( #Sql );
SELECT * FROM #tmp_prueba
Here are the changes. FIrst, I select everything from the temproary table in the #sql query. Second, I create a temporary table (with the same name in this case) to hold the results. Now, I can insert the results from the execute into the table. Voila! The data is there.
Temp table are created on Tempdb, therefor you can also do this:
SET #Sql = 'SELECT 1 AS id, ''123'' AS value INTO ##tmp_prueba'
EXECUTE ( #Sql )
Select * from tempdb..##tmp_prueba