How can I insert the result of below dynamic openquery into an existing table
DECLARE #TSQL varchar(8000), #VAR char(2)
SELECT #VAR = 'CA'
SELECT #TSQL = 'SELECT * FROM OPENQUERY(MyLinkedServer,''SELECT * FROM pubs.dbo.authors WHERE state = ''''' + #VAR + ''''''')'
EXEC (#TSQL)
I tried Insert into but didn't work.
INSERT INTO TableA
SELECT *
FROM (EXEC (#TSQL))
You were pretty close
DECLARE #TSQL varchar(8000), #VAR char(2)
SELECT #VAR = 'CA'
SELECT #TSQL = 'SELECT * FROM OPENQUERY(MyLinkedServer,''SELECT * FROM pubs.dbo.authors WHERE state = ''''' + #VAR + ''''''')'
INSERT INTO TableA
EXEC (#TSQL)
You can do it all in the dynamic string to avoid the INSERT EXEC statement
DECLARE #TSQL varchar(8000), #VAR char(2)
SELECT #VAR = 'CA'
SELECT #TSQL = 'INSERT INTO TableA SELECT * FROM OPENQUERY(MyLinkedServer,''SELECT * FROM pubs.dbo.authors WHERE state = ''''' + #VAR + ''''''')'
EXEC (#TSQL)
Related
Application: MS SSMS version: 18.12.1
Windows 10
I have Table_Name1 that contains the below info
col1Name
col2Name
col3Name
-,99
fred
1,23
col1 - col2 - col3 are all string datatype
col1 ordinal value = 1
col2 ordinal value = 2
col3 ordinal value = 3
I used the below code to retrieve the columns names from TABLE_NAME1 that were related to monetary values and placed those columns into TABLE_NAME2
DROP TABLE IF EXISTS STAGE.DBO.TABLE_NAME2<BR>
SELECT SC.NAME AS COLUMN_NAME<BR>
,SC.COLORDER AS COLUMN_ORDINAL<BR>
,CAST(ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS SMALLINT) AS ROW_NUM<BR>
INTO STAGE.DBO.TABLE_NAME2<BR>
FROM SYSOBJECTS AS SO<BR>
INNER JOIN SYSCOLUMNS AS SC ON SO.ID = SC.ID<BR>
WHERE SO.XTYPE = 'U'<BR>
AND SO.NAME = 'TABLE_NAME2'<BR>
AND SC.COLORDER IN (1,3)<BR>
ORDER BY SC.COLORDER, SC.NAME<BR>
TABLE_NAME2 contains the following info
column_name
column_ordinal
row_num
col1Name
1
1
col2Name
3
2
What I want to do: loop through TABLE_NAME1 column names and if there is a match with a value in TABLE_NAME2, then return that column name and assign it to a variable. Use the variable in an UPDATE TABLE statement to replace the comma (,) with a dot (.)
Below is what i tried: to have the result assigned to a variable
DECLARE #TABLE_NAME1 NVARCHAR(MAX)
DECLARE #TABLE_NAME2 NVARCHAR(MAX)
DECLARE #SQLQRY1 NVARCHAR(MAX)
DECLARE #LOOP1 SMALLINT
DECLARE #TABLE_ROW_COUNT1 SMALLINT
DECLARE #XTYPE1 CHAR(1)
DECLARE #COL_NAME1 NVARCHAR(MAX)
SET #TABLE_NAME1 = 'CH_IBRO_HOUSEHOLD_ACTIVITY_STG'
SET #TABLE_NAME2 = 'STAGE.DBO.CH_IBRO_HH_ACT_COL_NAME_STG'
SET #LOOP1 = 1
SET #XTYPE1 = 'U'
SET #TABLE_ROW_COUNT1 =2
WHILE #LOOP1 <= #TABLE_ROW_COUNT1
BEGIN
SET #SQLQRY1 = N'SELECT #COL_NAME1=TBL2.COLUMN_NAME
FROM ( SELECT SC.[NAME] AS COL_NAME, SC.COLORDER AS COL_ORDER
FROM SYSOBJECTS AS SO
INNER JOIN SYSCOLUMNS AS SC ON SO.ID = SC.ID
WHERE SO.XTYPE = '''+ #XTYPE1 +'''
AND SO.NAME = '''+ #TABLE_NAME1 +'''
) AS TBL1
INNER JOIN ( SELECT *
FROM '+ #TABLE_NAME2 +'
) AS TBL2 ON TBL2.COLUMN_NAME = TBL1.COL_NAME
AND TBL2.COLUMN_ORDINAL = TBL1.COL_ORDER
WHERE TBL2.ROW_NUM = ' + CAST(#LOOP1 AS NVARCHAR(MAX))
EXECUTE #COL_NAME1 = sp_executesql #SQLQRY1 OUTPUT
PRINT 'COL_NAME = '+ CAST(#COL_NAME1 AS VARCHAR);
PRINT 'LOOP NUMBER = '+ CAST(#LOOP1 AS VARCHAR);
/* INCREMENT */
SET #LOOP1 = #LOOP1 + 1
END
Thank you all for your support as I am new to T-SQL
thank you for the documentation. It helped alot. Just wanted to post most solution.
STEP1: CREATE TEMPORARY TABLE THAT WILL CONTIAN THE NAME OF THE COLUMNS THAT ARE SUPPOSE TO HAVE NUMERIC DATA
USE [STAGE]
DROP TABLE IF EXISTS STAGE.DBO.CH_IBRO_HOUSEHOLD_ACTIVITY_COLUMN_NAME_STG
SELECT SC.NAME AS COLUMN_NAME
,SC.COLORDER AS COLUMN_ORDINAL
,CAST(ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS SMALLINT) AS ROW_NUM
INTO STAGE.DBO.CH_IBRO_HOUSEHOLD_ACTIVITY_COLUMN_NAME_STG
FROM SYSOBJECTS AS SO
INNER JOIN SYSCOLUMNS AS SC ON SO.ID = SC.ID
WHERE SO.XTYPE = 'U'
AND SO.NAME = 'CH_IBRO_HOUSEHOLD_ACTIVITY_STG'
AND SC.COLORDER IN (26,27,28,29,30,31,32,33,34,35,36,39,40,45,46,47,48,49,50,54,55,56,59,60,61,64,65,66,83,84)
ORDER BY SC.COLORDER, SC.NAME
STEP2: APPLY GLOBAL SCRUBBING LOGIC TO THE COLUMNS CONTIAN NUMERIC DATA
USE [STAGE]
DECLARE #TABLE_NAME1 NVARCHAR(MAX)
DECLARE #TABLE_NAME2 NVARCHAR(MAX)
DECLARE #SQLQRY1 NVARCHAR(MAX)
DECLARE #LOOP1 SMALLINT
DECLARE #TABLE_ROW_COUNT1 SMALLINT
DECLARE #XTYPE1 CHAR(1)
DECLARE #COL_NAME1 NVARCHAR(MAX)
SET #TABLE_NAME1 = 'CH_IBRO_HOUSEHOLD_ACTIVITY_STG'
SET #TABLE_NAME2 = 'STAGE.DBO.CH_IBRO_HOUSEHOLD_ACTIVITY_COLUMN_NAME_STG'
SET #LOOP1 = 1
SET #XTYPE1 = 'U'
SET #TABLE_ROW_COUNT1 = (SELECT COUNT(*) FROM STAGE.DBO.CH_IBRO_HOUSEHOLD_ACTIVITY_COLUMN_NAME_STG)
DECLARE #ParmDefinition nvarchar(500);
SELECT #ParmDefinition = N'#COL_NAME1 NVARCHAR(MAX) OUTPUT';
WHILE #LOOP1 <= #TABLE_ROW_COUNT1
BEGIN
SET #SQLQRY1 = N'SELECT #COL_NAME1=TBL2.COLUMN_NAME
FROM ( SELECT SC.[NAME] AS COL_NAME, SC.COLORDER AS COL_ORDER
FROM SYSOBJECTS AS SO
INNER JOIN SYSCOLUMNS AS SC ON SO.ID = SC.ID
WHERE SO.XTYPE = '''+ #XTYPE1 +'''
AND SO.NAME = '''+ #TABLE_NAME1 +'''
) AS TBL1
INNER JOIN ( SELECT *
FROM '+ #TABLE_NAME2 +'
) AS TBL2 ON TBL2.COLUMN_NAME = TBL1.COL_NAME
AND TBL2.COLUMN_ORDINAL = TBL1.COL_ORDER
WHERE TBL2.ROW_NUM = ' + CAST(#LOOP1 AS NVARCHAR(MAX))
EXEC sp_executesql #SQLQRY1, #ParmDefinition, #COL_NAME1 OUTPUT
PRINT 'COL_NAME = '+ CAST(#COL_NAME1 AS VARCHAR);
PRINT 'LOOP NUMBER = '+ CAST(#LOOP1 AS VARCHAR);
/* REMOVE ALL LEADING AND TRAILING SPACES */
UPDATE STAGE.DBO.CH_IBRO_HOUSEHOLD_ACTIVITY_STG
SET #COL_NAME1 = LTRIM(RTRIM(#COL_NAME1))
/* REMOVE ALL ASCII CHAR (13) PRESS ENTER */
UPDATE STAGE.DBO.CH_IBRO_HOUSEHOLD_ACTIVITY_STG
SET #COL_NAME1 = REPLACE(#COL_NAME1,CHAR(13),'')
/* REMOVE ALL ASCII CHAR (10) LINE FEED */
UPDATE STAGE.DBO.CH_IBRO_HOUSEHOLD_ACTIVITY_STG
SET #COL_NAME1 = REPLACE(#COL_NAME1,CHAR(10),'')
/* REMOVE ALL ASCII CHAR (9) HORIZONTAL TAB */
UPDATE STAGE.DBO.CH_IBRO_HOUSEHOLD_ACTIVITY_STG
SET #COL_NAME1 = REPLACE(#COL_NAME1,CHAR(9),'')
/* REMOVE ALL LEADING AND TRAILING SPACES - 2ND PASS */
UPDATE STAGE.DBO.CH_IBRO_HOUSEHOLD_ACTIVITY_STG
SET #COL_NAME1 = LTRIM(RTRIM(#COL_NAME1))
/* INCREMENT */
SET #LOOP1 = #LOOP1 + 1
END
I wanted to create a view from the system tables, I could output the syntax which I want to run but how could I run that output command?
I created the following query which output the syntax to create the table
SELECT
'CREATE VIEW [Uti_John].[Vw_' + x.table_name +']' +
' AS SELECT * FROM [' + x.schema_name + '].[' + x.table_name +']'
FROM
(
SELECT SCHEMA_NAME(schema_id) AS schema_name
,name AS table_name
FROM sys.tables
WHERE name like 'T%'
and SCHEMA_NAME(schema_id) = 'dbo'
) x
Output
CREATE VIEW [Uti_John].[Vw_TNAME] AS SELECT * FROM [dbo].[TNAME]
CREATE VIEW [Uti_John].[Vw_TClient] AS SELECT * FROM [dbo].[TClient]
CREATE VIEW [Uti_John].[Vw_TClaim] AS SELECT * FROM [dbo].[TTClaim]
CREATE VIEW [Uti_John].[Vw_TInsurance] AS SELECT * FROM [dbo].[TTInsurance]
CREATE VIEW [Uti_John].[Vw_Ttest] AS SELECT * FROM [dbo].[Ttest]
copying manually one by one output of this creates the view but how could I run this output in a loop and create automatically?
You can use the sys.views view to check if the view already exists.
DECLARE #SQL NVARCHAR(max)='*';
WHILE #SQL IS NOT NULL
BEGIN
SET #SQL = NULL;
SELECT #SQL =
'CREATE VIEW [Uti_John].[Vw_' + x.table_name +']' +
' AS SELECT * FROM [' + x.schema_name + '].[' + x.table_name +']'
FROM
(
SELECT SCHEMA_NAME(schema_id) AS schema_name
,t.name AS table_name
FROM sys.tables t
WHERE t.name like 't%'
and SCHEMA_NAME(t.schema_id) = 'dbo'
AND NOT EXISTS ( SELECT *
FROM sys.views v
WHERE v.name = 'Vw_' + t.name
AND OBJECT_SCHEMA_NAME(v.object_id) = 'Uti_John'
)
) x
EXEC sp_executesql #SQL;
PRINT #SQL;
END ;
Select all tables which begin with "coc"
I wanna know how to select all tables which begin with "coc". There are coc1, coc2, coc3.... tables in DB.
SELECT * FROM coc...
You can do it as follows:
SELECT *
FROM coc1
UNION
SELECT *
FROM coc2
UNION
SELECT *
FROM coc3
or
SELECT
TABLE_NAME
FROM
information_schema.TABLES
WHERE
table_schema = [DB_NAME]
AND
TABLE_NAME LIKE 'coc%'
I have a SP that is supposed to compare 2 temp tables generated from a function to another table. My issue is that instead of stepping through each temp table it goes through both at the same time. I am not sure how to write the code to step through each table one at a time to get the desired results.
DROP PROCEDURE uspJudgments;
GO
CREATE PROCEDURE uspJudgments
#fullName varchar(100), #fullName1 varchar(100)
AS
BEGIN
SELECT *
INTO #tmpFullname
FROM dbo.DelimitedSplit8K(#fullName, ',')
SELECT *
INTO #tmpFullname1
FROM dbo.DelimitedSplit8K(#fullName1, ',')
SELECT *
FROM #tmpFullName
SELECT *
FROM #tmpFullName1
DECLARE #MaxRownum int
SET #MaxRownum = (SELECT MAX(ItemNumber) FROM #tmpFullname)
DECLARE #Iter int
SET #Iter = (SELECT MIN(ItemNumber) FROM #tmpFullname)
DECLARE #MaxRownum1 int
SET #MaxRownum1 = (SELECT MAX(ItemNumber) FROM #tmpFullname1)
DECLARE #Iter1 int
SET #Iter1 = (SELECT MIN(ItemNumber) FROM #tmpFullname1)
DECLARE #Name varchar(25)
DECLARE #Name1 varchar(25)
WHILE #Iter <= #MaxRownum AND #iter1 <= #Maxrownum1
BEGIN
SET #Name = (SELECT Item FROM #tmpFullname WHERE ItemNumber = #Iter)
SET #Name1 = (SELECT Item FROM #tmpFullname1 WHERE ItemNumber = #Iter1)
SELECT *
--INTO #tmpDefSelect
FROM defendants_ALL
WHERE combined_name LIKE '%' + #Name + '%' AND combined_name LIKE '%' + #Name1 + '%';
SET #Iter = #Iter + 1
SET #Iter1 = #Iter1 + 1
END
END
DROP TABLE #tmpFullname
DROP TABLE #tmpFullname1
EXEC uspJudgments #fullName = 'grein,smit', #fullName1 = 'joh,jon,j.'
I need to get ALL results for grein -- joh, jon, j. AND smit, joh, jon, j.
Currently the above code only returns grein joh AND smit, jon.. In our database that returns no results for the first combination and 38 results for jonathon smith and jon smith. How do I properly step through each temp table to get the desired results?
You only get the two combinations grein joh and smith jon because of the way you are iterating through #Iter and #iter1. You increment both of them at the same time. You need a nested loop like this:
declare #start_val integer = #iter1
while #Iter <= MaxRownum
begin
set #iter1 = #start_val
while #iter1 <= #Maxrownum1
begin
set #Name = ...
set #Name1 = ...
...
set #iter1 = #iter1 + 1
end
set #Iter = #Iter + 1
end
But I don't think you even need the WHILE loops:
select d.*
from defendants_ALL, #tmpFullname t1, #tmpFullname1 t2
where d.combined_name = t1.Item + ' ' + t2.Item
Or (if you need to still use LIKE):
select d.*
from defendants_ALL, #tmpFullname t1, #tmpFullname1 t2
where d.combined_name like '%' + t1.Item + '%'
and d.combined_name like '%' + t2.Item + '%'
(All SQL is untested...)
I need to summarize numbers like
CREATE TABLE #t(num int);
INSERT #t
SELECT 10001 UNION ALL
SELECT 10002 UNION ALL
SELECT 10003 UNION ALL
SELECT 10004 UNION ALL
SELECT 10005 UNION ALL
SELECT 10006 UNION ALL
SELECT 10007 UNION ALL
SELECT 10008 UNION ALL
SELECT 10009 UNION ALL
SELECT 10010 UNION ALL
SELECT 10020 UNION ALL
SELECT 10030 UNION ALL
SELECT 10040 UNION ALL
SELECT 10041 UNION ALL
SELECT 10042 UNION ALL
SELECT 10043 UNION ALL
SELECT 10050 UNION ALL
SELECT 10060 UNION ALL
SELECT 10070 UNION ALL
SELECT 10075 UNION ALL
SELECT 10076 UNION ALL
SELECT 10077;
--DROP TABLE #T;
to a simpler form in such a way that result would be.
10001-10010, 10020, 10030, 10040-10043, 10050, 10060, 10070, 10075-10077
Any help would be highly appreciated.
Try this:
WITH CTE1 AS
(
SELECT *, num - ROW_NUMBER() OVER(ORDER BY num) Corr
FROM #t
), CTE2 AS
(
SELECT MIN(num) MinNum, MAX(num) MaxNum, Corr
FROM CTE1
GROUP BY Corr
)
SELECT CAST(MinNum AS VARCHAR) +
CASE WHEN MaxNum != MinNum THEN ' - ' + CAST(MaxNum AS VARCHAR) ELSE '' END Res
FROM CTE2
DECLARE #Result VARCHAR(MAX);
WITH q AS (
SELECT
Num,
Num - (ROW_NUMBER() OVER (ORDER BY Num)) AS RowNumber
FROM
#t
)
SELECT
#Result = ISNULL(#Result + ',', '') +
CASE WHEN MIN(Num) != MAX(Num)
THEN CAST(MIN(Num) AS VARCHAR) + '-' + CAST(MAX(Num) AS VARCHAR)
ELSE CAST(MIN(Num) AS VARCHAR)
END
FROM q
GROUP BY RowNumber
PRINT #Result
-- Or... SELECT #Result.. whichever.
Try a cursor.
Run your script to create a table, then this
DECLARE cur CURSOR FOR
SELECT num FROM #t
OPEN cur
DECLARE #nm INT;
DECLARE #start INT;
DECLARE #prev INT;
DECLARE #retVal VARCHAR(MAX);
SET #retVal = '';
FETCH NEXT FROM cur INTO #nm
SET #prev = NULL;
SET #start = NULL;
WHILE (##fetch_status = 0)
BEGIN
IF (#prev IS NOT NULL)
BEGIN
IF (#prev = #nm - 1)
BEGIN
SET #prev = #nm;
END
ELSE
BEGIN
IF (#start = #prev)
SET #retVal = #retVal + CAST(#start AS VARCHAR) + ', '
ELSE
SET #retVal = #retVal + CAST(#start AS VARCHAR) + ' - ' + CAST(#prev AS VARCHAR) + ', '
SET #prev = #nm;
SET #start = #nm;
END
END
ELSE
BEGIN
SET #prev = #nm;
SET #start = #nm;
END
--PRINT(#nm)
FETCH NEXT FROM cur INTO #nm
END
CLOSE cur
DEALLOCATE cur
IF (#start = #prev)
SET #retVal = #retVal + CAST(#start AS VARCHAR) + ', '
ELSE
SET #retVal = #retVal + CAST(#start AS VARCHAR) + ' - ' + CAST(#prev AS VARCHAR) + ', '
IF (LEN(#retVal) > 1)
SET #retVal = SUBSTRING(#retVal, 1, LEN(#retVal) - 1)
PRINT(#retVal)