Setting variables in temp tables - mysql

Can anybody help on a problem I am having. For the software i am using it won't accept temp tables unless the table is created and inserted into just like i tried with this.
Before i put in the create table and insert into just the table it works fine but when i try this it says the table already exists.
Can anybody see what i am doing wrong and can advise, it's the variables in my temp tables that is throwing me off.
declare #bt_id varchar(20) = '110';
declare #ms_id varchar(20) = '2';
declare #sqlstr varchar(max) = '';
if object_id('tempdb..#measure_raw') is not null
drop table #measure_raw
CREATE TABLE #measure_raw(
meas_id INT,
column_name VARCHAR (255),
vlu_txt VARCHAR (255),
batch_id INT,
row_num INT,
)
insert into #measure_raw
set #sqlstr = 'select det.meas_id,col.tbl_nm+''.''+col.logged_nm as column_name, det.vlu_txt, det.batch_id, '
+ 'case when (det.row_num is null) then 1 else det.row_num end as row_num '
+ 'into #measure_raw from detail_t det '
+ 'inner join column_t col on col.col_id=det.col_id inner join measure_t rul on rul.meas_id=det.meas_id '
+ 'where det.batch_id = ' + #bt_id + ' '
if #ms_id <> '0'
set #sqlstr = #sqlstr + 'and det.meas_id = ' + #ms_id + ' '
set #sqlstr = #sqlstr + 'order by '
+ 'det.batch_id, det.meas_id, det.row_num, col.tbl_nm, col.logged_nm'
exec(#sqlstr)

Related

Field Not Generated in SRRS from Stored Procedure

I Exec one procedure to generate column and use in SRRS dataset :
here's my SP :
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[CrossTab_MultiLV]
( #Select varchar(2000),
#Pivots1Col varchar(100),
#Summaries varchar(500),
#GroupBy varchar(100),
#OtherCols varchar(1000) = Null)
AS
set nocount on
set ansi_warnings on
declare #Vals varchar(8000);
set #Vals = '';
set #OtherCols= isNull(', ' + #OtherCols,'')
create table #temp (Pivots1 varchar(100))
insert into #temp
exec ('select distinct convert(varchar(100),' + #Pivots1Col + ',101) as Pivots1 FROM (' + #Select + ') A')
select #Vals = #Vals + ', ' +
replace(replace(#Summaries,'(','(CASE WHEN ' + #Pivots1Col + '=''' + Pivots1 + ''' THEN '),')[', ' END) as [' + Pivots1 )
from #Temp
order by Pivots1
drop table #Temp
exec ( 'select ' + #GroupBy + #OtherCols + #Vals +
' from (' + #Select + ') A GROUP BY ' + #GroupBy)
set nocount off
set ansi_warnings on
from sp above I just want to process something and generate field by those SP Produce multiple column , but only show the two first column
:
range TotalAccount CL_Only CL_Only_Have_Rate CL_Only_No_Rate EU_CL EU_CL_Have_Rate EU_CL_No_Rate EU_Only EU_Only_Have_Rate EU_Only_No_Rate
12 3 1 1 0 2 2 0 0 0 0
it'll only show : range TotalAccount column , is there any mistake in my stored procedure ??
I would abandon the dynamic stored procedure design - SSRS does not work with these.
Instead I would present the data with fixed columns and use a Column Group in the SSRS design.

Creating 'util' - stored procedure section, as with .net helper classes

A few minutes ago I was only searching for a simple syntax (SQL server) query that will copy a table Row .
This is usually done from time to time, when working on a ASP.net project, testing data with queries
inside the SQL SERVER management studio . so one of the routine actions is copying a row, altering the required columns to be different from each other, then testing data with queries
So I've encountered - this stored procedure- ,as answer by Dan Atkinson
but adding it to where all non testing purpose are stored lead me to think
is it possible to store them in sorted order so I could Distinguish
'utils' or 'testingPurpose' ones from those used in projects
(default folder inside managment treeview is Programmabilty) could this be another folder too
or this is not an option ?
if not , I thought of Utils. prefix like that (if no other way exist)
dbo.Utils.CopyTableRow
dbo.Utils.OtherRoutineActions ....
Or there's a designated way to achieve what I was thinking of.
this is a first "Util" stored procedure i've made , found it's only solution
prefexing it via Util_
ALTER PROCEDURE [dbo].[Utils_TableRowCopy](
#TableName VARCHAR(50) ,
#RowNumberToCopy INT
)
AS
BEGIN
declare #RowIdentity sysname =
(SELECT name FROM sys.identity_columns WHERE object_id = object_id(#TableName)
)
DECLARE #columns VARCHAR(5000), #query VARCHAR(8000);
SET #query = '' ;
SELECT #columns =
CASE
WHEN #columns IS NULL THEN column_name
ELSE #columns + ',' + column_name
END
FROM INFORMATION_SCHEMA.COLUMNS
WHERE (
TABLE_NAME = LTRIM(RTRIM(#TableName))
AND
column_name <> LTRIM(RTRIM(#RowIdentity))
);
SET #query = 'INSERT INTO ' + #TableName + ' (' + #columns + ') SELECT ' + #columns + ' FROM ' + #TableName + ' WHERE ' + #RowIdentity + ' = ' + CAST(#RowNumberToCopy AS VARCHAR);
--SELECT SCOPE_IDENTITY();
declare #query2 VARCHAR(100) = ' Select Top 1 * FROM '+ #TableName +' Order BY ' + #RowIdentity + ' desc' ;
EXEC (#query);
EXEC (#query2);
END

insert command SQL server -identity Pkey autoincrement - column name by type , in "where condition"

i would like to alter a stored procedure so i will not suplly the identity column name
INSERT INTO tablName ..... WHERE IDENTITY_Column = 10
can i tell sql server managment studio to just refer to the IDENTITY column so it will find
it by its type which is (at least in my tables a default) autoincremet PK ID type
You haven't really given enough code for us to see what you are trying to do but from the snippet in the question.
WHERE IDENTITY_Column = 10
You can just use
WHERE $IDENTITY = 10
for that (to filter against an identity column without specifying the name).
If you do actually need to lookup the column name then an easier way, avoiding deprecated views is
SELECT name
FROM sys.identity_columns
WHERE object_id = object_id('dbo.YourTable')
found this information by now .
that is the plain and simple version .
declare #tblName sysname = '______'--<== enter a table name
declare #NameOfIDColumn sysname =
(
SELECT Name
FROM syscolumns
WHERE COLUMNPROPERTY( id ,name, 'IsIdentity') = 1 and OBJECT_NAME(id)= #tblName )
select #NameOfIDColumn AS 'result'
you could add this as an option to display last row of a table soretd by its record#
declare #query VARCHAR(100) = 'Select Top 1 * FROM '+ #tblName +' Order BY ' + #IdentColumnName + ' desc' ;
EXEC (#query);
and to play around or even make it as a test page in a .net project
make this one as a stored proc that will outpout a message to a test page .
declare #tblName sysname = '______'--<== enter a table name
declare #IdentColumnName sysname =
(
SELECT Name
FROM syscolumns
WHERE COLUMNPROPERTY( id ,name, 'IsIdentity') = 1 and OBJECT_NAME(id)= #tblName )
declare #result VARCHAR (50) = #tblName + ' Identity Column is ' + #IdentColumnName;
select #result AS 'result'
and with a shorter version of "idntity column search", by Martin Smith
declare #tblName sysname = '______'--<== enter a table name
declare #IdentColumnName sysname =
(SELECT name FROM sys.identity_columns WHERE object_id = object_id(#TableName))
declare #result VARCHAR (50) = #tblName + ' Identity Column is ' + #IdentColumnName;
select #result AS 'result'
this is related to a table copy trick i was trying to pull via stored procedure.
USE [YourDataBaseName]
GO
/****** Object: StoredProcedure [dbo].[Utils_TableRowCopy] Script Date: 10/03/2012 18:26:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Utils_TableRowCopy](
#TableName VARCHAR(50) ,
#RowNumberToCopy INT
)
AS
BEGIN
declare #RowIdentity sysname =
(
SELECT name FROM sys.identity_columns WHERE object_id = object_id(#TableName)
)
DECLARE #columns VARCHAR(5000), #query VARCHAR(8000);
SET #query = '' ;
SELECT #columns =
CASE
WHEN #columns IS NULL THEN column_name
ELSE #columns + ',' + column_name
END
FROM INFORMATION_SCHEMA.COLUMNS
WHERE (
TABLE_NAME = LTRIM(RTRIM(#TableName))
AND
column_name <> LTRIM(RTRIM(#RowIdentity))
);
SET #query = 'INSERT INTO ' + #TableName + ' (' + #columns + ') SELECT ' + #columns + ' FROM ' + #TableName + ' WHERE ' + #RowIdentity + ' = ' + CAST(#RowNumberToCopy AS VARCHAR);
--SELECT SCOPE_IDENTITY();
declare #query2 VARCHAR(100) = ' Select Top 1 * FROM '+ #TableName +' Order BY ' + #RowIdentity + ' desc' ;
EXEC (#query);
EXEC (#query2);
END

sql update with dynamic column names

EDIT: Database names have been modified for simplicity
I'm trying to get some dynamic sql in place to update static copies of some key production tables into another database (sql2008r2). The aim here is to allow consistent dissemination of data (from the 'static' database) for a certain period of time as our production databases are updated almost daily.
I am using a CURSOR to loop through a table that contains the objects that are to be copied into the 'static' database.
The prod tables don't change that frequently, but I'd like to make this somewhat "future proof" (if possible!) and extract the columns names from INFORMATION_SCHEMA.COLUMNS for each object (instead of using SELECT * FROM ...)
1) From what I have read in other posts, EXEC() seems limiting, so I believe that I'll need to use EXEC sp_executesql but I'm having a little trouble getting my head around it all.
2) As an added extra, if at all possible, i'd also like to exclude some columns for particular tables (structures vary slightly in the 'static' database)
here's what i have so far.
when executed, #colnames returns NULL and therefore #sql returns NULL...
could someone guide me to where i might find a solution?
any advice or help with this code is much appreciated.
CREATE PROCEDURE sp_UpdateRefTables
#debug bit = 0
AS
declare #proddbname varchar(50),
#schemaname varchar(50),
#objname varchar(150),
#wherecond varchar(150),
#colnames varchar(max),
#sql varchar(max),
#CRLF varchar(2)
set #wherecond = NULL;
set #CRLF = CHAR(10) + CHAR(13);
declare ObjectCursor cursor for
select databasename,schemaname,objectname
from Prod.dbo.ObjectsToUpdate
OPEN ObjectCursor ;
FETCH NEXT FROM ObjectCursor
INTO #proddbname,#schemaname,#objname ;
while ##FETCH_STATUS=0
begin
if #objname = 'TableXx'
set #wherecond = ' AND COLUMN_NAME != ''ExcludeCol1'''
if #objname = 'TableYy'
set #wherecond = ' AND COLUMN_NAME != ''ExcludeCol2'''
--extract column names for current object
select #colnames = coalesce(#colnames + ',', '') + QUOTENAME(column_name)
from Prod.INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = + QUOTENAME(#objname,'') + isnull(#wherecond,'')
if #debug=1 PRINT '#colnames= ' + isnull(#colnames,'null')
--replace all data for #objname
--#proddbname is used as schema name in Static database
SELECT #sql = 'TRUNCATE TABLE ' + #proddbname + '.' + #objname + '; ' + #CRLF
SELECT #sql = #sql + 'INSERT INTO ' + #proddbname + '.' + #objname + ' ' + #CRLF
SELECT #sql = #sql + 'SELECT ' + #colnames + ' FROM ' + #proddbname + '.' + #schemaname + '.' + #objname + '; '
if #debug=1 PRINT '#sql= ' + isnull(#sql,'null')
EXEC sp_executesql #sql
FETCH NEXT FROM ObjectCursor
INTO #proddbname,#schemaname,#objname ;
end
CLOSE ObjectCursor ;
DEALLOCATE ObjectCursor ;
P.S. i have read about sql injection, but as this is an internal admin task, i'm guessing i'm safe here!? any advice on this is also appreciated.
many thanks in advance.
You have a mix of SQL and dynamic SQL in your query against information_schema. Also QUOTENAME isn't necessary in the where clause and will actually prevent a match at all, since SQL Server stores column_name, not [column_name], in the metadata. Finally, I'm going to change it to sys.columns since this is the way we should be deriving metadata in SQL Server. Try:
SELECT #colnames += ',' + name
FROM Prod.sys.columns
WHERE OBJECT_NAME([object_id]) = #objname
AND name <> CASE WHEN #objname = 'TableXx' THEN 'ExcludeCol1' ELSE '' END
AND name <> CASE WHEN #objname = 'TableYy' THEN 'ExcludeCol2' ELSE '' END;
SET #colnames = STUFF(#colnames, 1, 1, '');

SQL script to rebuild indexes - Incorrect syntax near the keyword 'Group'

I have a fairly basic SQL script to rebuild all the table indexes under various schema within a database. The script seems to work on the 183 indexes I have, but returns the error message
(183 row(s) affected)
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'Group'
Can anyone explain why and provide a solution?
USE RedGateMonitor;
GO
declare #db varchar(150)
declare #tmp TABLE(recnum int IDENTITY (1,1), tableschema varchar(150), tablename varchar(150))
insert #tmp (tableschema, tablename)
SELECT TABLE_SCHEMA, TABLE_NAME FROM information_schema.tables where TABLE_TYPE = 'BASE TABLE'
ORDER By TABLE_SCHEMA
declare #X int, #table varchar(150), #cmd varchar(500), #schema varchar(150)
set #X = 1
While #X <= (select count(*) from #tmp) BEGIN
set #db = 'RedGateMonitor'
set #table = (select tablename from #tmp where recnum = #X)
set #schema = (select tableschema from #tmp where recnum = #X)
set #cmd = 'ALTER INDEX ALL ON ' + #db + '.' + #schema + '.' + #table + ' REBUILD'
EXECUTE(#cmd)
set #X = #X + 1
END
I agree with both of Mitch's comments:
(1) you should be using an existing solution for this instead of reinventing the wheel.
(2) if you aren't going to follow basic rules for identifiers (e.g. not naming schemas or tables with reserved words), you need to properly escape them. A quick fix would be:
set #cmd = 'ALTER INDEX ALL ON ' + quotename(#db)
+ '.' + quotename(#schema)
+ '.' + Quotename(#table) +  ' REBUILD;';
A slightly better fix would be the following, with no need for #temp tables or looping:
DECLARE #sql NVARCHAR(MAX) = N'';
SELECT #sql += N'ALTER INDEX ALL ON ' + QUOTENAME(#db)
+ '.' + QUOTENAME(SCHEMA_NAME([schema_id])
+ '.' + QUOTENAME(name) + ' REBUILD;';
EXEC sp_executesql;
But I don't think you need to rebuild all of the indexes on all of the tables in the Red Gate database. Scripts like Ola's will help you be more efficient about which indexes to rebuild, which to reorganize, and which to leave alone.