Table variable and exec - tsql

How can I use a table variable while executing a command string?
DECLARE #FileIDs TABLE
(
File_ID int
)
insert into #FileIDs select ID from Files where Name like '%bla%';
DECLARE #testquery as varchar(max);
set #testquery = 'select * from #FileIDs';
exec(#testquery);
returns the following error
Msg 1087, Level 15, State 2, Line 1
Must declare the table variable "#FileIDs".

The table #FileIDs is not in the scope of exec(#testquery).
That's why you have that problem.
To solve this problem you may use a temporary table:
CREATE table #FileIDs
(
File_ID int
)
insert into #FileIDs select ID from Files where Name like '%bla%';
DECLARE #testquery as varchar(max);
set #testquery = 'select * from #FileIDs';
exec(#testquery);
drop table #FileIDs
or put the table in the scope:
DECLARE #sql nvarchar(2000)
SET #sql='DECLARE #FileIDs TABLE ( File_ID int);'
SET #sql=#sql+'insert into #FileIDs select ID from Files where Name like ''%bla%'';'
set #sql=#sql+ 'select * from #FileIDs;'
EXECUTE sp_executesql #sql

Indeed table is out of the scope, try this:
DECLARE #sql nvarchar(2000)
SET #sql='DECLARE #FileIDs TABLE ( File_ID int);'
SET #sql=#sql+'insert into #FileIDs select ID from Files where Name like ''%bla%'';'
set #sql=#sql+ 'select * from #FileIDs;'
EXECUTE sp_executesql #sql

CREATE table #FileIDs
(
File_ID int
)
insert into #FileIDs select ID from Files where Name like '%bla%';
DECLARE #testquery as varchar(max);
set #testquery = 'select * from #FileIDs';
exec(#testquery);
drop table #FileIDs

Related

Taking result from SQL/T-SQL Subselect into the parent select statement

I want to extend ListA with Company coming from #MyList.CompanyNo, plese refer to the code listing
Data&Init:
begin /*Just the init data*/
DECLARE #MyList TABLE (Mail nvarchar(max), CompanyNo int)
INSERT INTO #MyList VALUES ('...com',20)
INSERT INTO #MyList VALUES ('...com',230)
INSERT INTO #MyList VALUES ('...com',120)
INSERT INTO #MyList VALUES ('...com',223)
end
--DECLARE
DECLARE #ListA TABLE (Id nvarchar(max), Mail nvarchar(max))
DECLARE #ListB TABLE (Id nvarchar(max), Mail nvarchar(max),Company int)
Starting point(this works):
INSERT INTO #ListA(Id,Mail) select someId,name from [somedb].[dbo].aers where name IN (SELECT Mail FROM #MyList)
I was trying to do it the following way:
INSERT INTO #ListB(Id,Mail,Company) select someId,name,#MyList.CompanyNo from [somedb].[dbo].aers where name IN (SELECT Mail FROM #MyList)
So actually I want to extend ListB with the corrosponding #MyList.CompanyNo.
Thanks, what can I do ?
You could use JOIN based on condition from WHERE:
INSERT INTO #ListB(Id,Mail,Company)
select a.someId,a.name,m.CompanyNo
from [somedb].[dbo].aers a
join #MyList m
ON a.name = m.Mail;

dynamic Select statement on declared table variable - SYBASE

I have one declared table variable in stored procedure,(sybase database). Data is populated in that table as needed. But now I want to select particular columns based on different conditions. I am trying dynamic SQL to do the same but not working. Can it go like I am assuming?
ALTER PROCEDURE "dbo"."sp_userMenus"
#fundName VARCHAR(20) , #userName VARCHAR(20)
AS
BEGIN
declare #tableData as table (
id int IDENTITY(1,1),
[menuDisplayName] nvarchar(100),
[menuOrder] int,
[menuType] nvarchar(100),
[parentVerticalMenu] nvarchar(100),
[parentHorizontalMenu] nvarchar(100),
[groupID] int,
[inDashboardAll] int,
[inDashboardOverview] int,
[inDetail] int,
[inSummary] int,
[isDetail] int,
[zOrder] int
)
--insert into #tableData
if #userName = 'ADMIN'
SET #SQLQuery = 'select *
from #tableData order by parentVerticalMenu, parentHorizontalMenu'
else
SET #SQLQuery = 'select menuDisplayName,menuOrder,menuType,parentVerticalMenu,parentHorizontalMenu
from #tableData order by parentVerticalMenu, parentHorizontalMenu'
EXEC sp_executesql #SQLQuery
END
getting error "Must declare the scalar variable "#tableData" OR Must declare the table variable "#tableData".
Change the code:
declare #tableData as table (
To:
CREATE TABLE #tableData (
Change the references from #tableData to #tableData
The temporary table will exist until the current session or procedure ends, or until its you drop it using drop table.
Remove the keyword 'as' prior to 'table'

MS SQL Server 2012 Trigger Syntax

I am working on HW assignment learning about triggers and am having problems with syntax on both insert and delete DML ForTriggers as follows:
CREATE TRIGGER tr_PERSON_ForInsert
ON PERSON
FOR INSERT
AS
BEGIN
DECLARE #SSN CHAR(9)
SELECT #SSN = SSN FROM inserted
DECLARE #NAME VARCHAR(50)
SELECT #NAME = NAME FROM inserted
DECLARE #USERNAME VARCHAR(50)
SELECT #USERNAME USERNAME FROM INSERTED
declare #time time(7)
select #time = time from inserted
insert into PERSON_DEL_LOG
VALUES ('New person with SSN = ' +
Cast(#SSN as NVARchar(9)) +
CAST(#NAME AS NVARCHAR(50)) +
cast(#username as nvarchar(50)) +
cast(#time as nvarchar(20))
)
END
INSERT INTO PERSON('012675543', 'MIKE', '5467896543', 'MUSEUM', 'INTEL',
'BLUECROSS', '987654321')
CREATE TRIGGER tr_PERSON_ForDELETE
ON PERSON
FOR DELETE
AS
BEGIN
DECLARE #SSN CHAR(9)
SELECT #SSN = SSN FROM DELETED
DECLARE #NAME VARCHAR(50)
SELECT #NAME = NAME FROM DELETED
insert into PERSON_DEL_LOG
VALUES ('New person with SSN = ' +
Cast(#SSN as nvarchar(9)) +
Cast(#NAME as VARCHAR(50)) + 'is added at ' +
cast(Getdate() as nvarchar(20))
)
END
DELETE FROM PERSON WHERE NAME = 987654321
SELECT * FROM PERSON_DEL_LOG
My PERSON_DEL_LOG table structure:
SSN, NAME, USERNAME, TIME
I need to know where exactly is my problem/s

Is it possible to use local table variables in a procedure inside an sql query contained in a VARCHAR variable?

I have the following code:
DECLARE #temp_table_1 TABLE (id int identity(0, 1), col_1 varchar(50)),
#txtVar VARCHAR(MAX)
INSERT INTO #temp_table_1
SELECT col_1 FROM table_1 -- This table_1 is a real table in the database.
Set #txtVar = 'SELECT * FROM #temp_table_1'
EXECUTE (#txtVar)
The error I get is
Declare variable #temp_table_1.
How can I fix this?
Set #txtVar = 'SELECT * FROM myTable WHERE column_value=''' + #var1 + ''''
This article will help you get a basic ideas of dynamic sql.
EDIT
It is not possible to use table variables in a dynamic query.
You have to use temporary table or Use custom TABLE type.
Temporary table
CREATE TABLE #temp_table_1
(
id INT IDENTITY(0, 1),
col_1 VARCHAR(50)
)
DECLARE #txtVar VARCHAR(MAX)
INSERT INTO #temp_table_1
SELECT col_1
FROM table_1 -- This table_1 is a real table in the database.
SET #txtVar = 'SELECT * FROM #temp_table_1'
EXECUTE (#txtVar)
DROP TABLE #temp_table_1
Custom Table Type
CREATE TYPE DefaultTable AS TABLE (ID INT IDENTITY(0, 1), COL_1 VARCHAR(50))
GO
-- Fill a var of that type with some test data
DECLARE #MyTable DefaultTable
INSERT #MyTable
SELECT col_1 FROM table_1 -- This table_1 is a real table in the database.
-- Now this is how you pass that var into dynamic statement
EXECUTE sp_executesql N'SELECT * FROM #MyTable',
N'#MyTable DefaultTable READONLY',
#MyTable

Adding Result Sets into One

I have a stored Procedure (Generate_Insert)which will output an Insert statement as output given a table name.
But Now I have created another procedure which looks like:
Create Procedure Inserts
As
Begin
EXEC Generate_Insert #Table = 'Admin'
EXEC Generate_Insert #Table = 'Impas'
EXEC Generate_Insert #Table = 'Asui'
EXEC Generate_Insert #Table = 'Alstd'
END
The sample output of
EXEC Generate_Insert #Table = 'Admin' is:
Insert into Admin(Ad_ID,Name,Desc) Values (1,'John','Employee')
The problem is when I execute this procedure I am getting result sets in different windows but i want the output as one result set.
How can I do this?
Assuming the output of Generate_Insert is a varchar(max)
you can do this inside Inserts:
create table #temp
(
insert_stmt varchar(max)
)
insert into #temp
EXEC Generate_Insert #Table = 'Admin'
insert into #temp
EXEC Generate_Insert #Table = 'Impas'
insert into #temp
EXEC Generate_Insert #Table = 'Asui'
insert into #temp
EXEC Generate_Insert #Table = 'Alstd'
select * from #temp