How to update table with dynamic column names? - sql-server-2012

The update statement below works as intended. However, I need to loop the statement upwards of 50 times. I'm trying to write a loop that will allow me to change the field that is getting set from Seg1 to SegX and the update the SubString(GoalBusinessSegment,(6*1)-5,5) AS 'Seg' to SubString(GoalBusinessSegment,(6*X)-5,5) AS 'Seg'
UPDATE [dbo].[MULTBUSSEGTEST]
SET Seg1 = SegTBL.Seg
FROM (SELECT DISTINCT GoalBusinessSegment,SubString(GoalBusinessSegment,(6*1)-5,5) AS 'Seg'
FROM [2017].[dbo].[WPGDM]
WHERE GoalID BETWEEN 22.1 AND 22.4 AND
LEFT(GoalBusinessSegment,1) = 'B' AND LEN(GoalBusinessSegment) > 5
) SegTBL
WHERE [dbo].[MULTBUSSEGTEST].SegID = SegTBL.GoalBusinessSegment
Below is my attempt at the loop.
DECLARE #LoopCount int
DECLARE #SegField varchar(255)
DECLARE #i int
DELETE FROM [dbo].[MULTBUSSEGTEST]
INSERT INTO [dbo].[MULTBUSSEGTEST]
SELECT DISTINCT GoalBusinessSegment AS 'SegID'
,NULL AS 'Seg1'
,NULL AS 'Seg2'
,NULL AS 'Tgt1'
,NULL AS 'Tgt2'
,NULL AS 'Act1'
,NULL AS 'Act2'
FROM [2017].[dbo].[WPGDM]
WHERE GoalID BETWEEN 22.1 AND 22.4 AND LEFT(GoalBusinessSegment,1) = 'B' AND LEN(GoalBusinessSegment) > 5
Set #LoopCount = (SELECT FLOOR(MAX(LEN(GoalBusinessSegment))/5)
FROM [2017].[dbo].[WPGDM]
)
WHILE #i <= #LoopCount
BEGIN
Set #SegField = 'Seg' + #LoopCount
UPDATE [dbo].[MULTBUSSEGTEST]
SET #SegField = SegTBL.Seg
FROM (SELECT DISTINCT GoalBusinessSegment
,SubString(GoalBusinessSegment,(6*#i)-5,5) AS 'Seg'
FROM [2017].[dbo].[WPGDM]
WHERE GoalID BETWEEN 22.1 AND 22.4 AND LEFT(GoalBusinessSegment,1) = 'B' AND LEN(GoalBusinessSegment) > 5
) SegTBL
WHERE [dbo].[MULTBUSSEGTEST].SegID = SegTBL.GoalBusinessSegment
SET #i = #i + 1
END
The loop produces all null values, what am I missing?

Realized that multiple fields and the update statement were not necessary. Problem solved.

Related

"Error" value on name and description creating strange functionality

I got a raw data file with its content looking like this:
MSN_Check,Text,25,MSN check
0,Text,1,(Result)
HWIMPL,Text,10,HWIMPL version reading
007F,Text,6,(Measure)
1,Text,1,(Result)
VHW,Text,10,FMT hardware version
494131383346,Text,10,(Measure)
0,Text,1,(Result)
TOTAL_VER,Text,25,Total version reading
313031303130,Text,6,(Measure)
1,Text,1,(Result)
CAL_MCU,Text,25,Total version reading
05,Text,6,(Measure)
Error,Text,25,Error
9.8499985089315E-07,Numeric,Float 3.3,(Measure)
CAL_EEPROM,Text,25,Total version reading
05,Numeric,Float 3.3,(Measure)
1,Text,1,(Result)
And I needed to extract and store in variables the name, example MSN_Check ,the description, example MSN check its result for example 0 and its measure , for example 007F but in some places I have results only or measures only so just spliting them wouldn't have helped.So my idea was:
First of all I created a template table named dbo.template that looks like this:
Name TestDescription Measure Result ID
----------------------------------------------
MSN_Check MSN check 0 1 1
HWIMPL HWIMPL version reading 1 1 2
VHW FMT hardware version 1 1 3
TOTAL_VER Total version reading 1 1 4
CAL_MCU Total version reading 1 0 5
Error Error 1 0 6
CAL_EEPROM Total version reading 1 1 7
In this table we have the name,description,if_measure(meaning 1 if we have a measure or 0 if we dont) and the if_result.And I made a query looking like this:
DECLARE #crlf AS CHAR(2) = CHAR(13) + CHAR(10)
declare #testname varchar(max),#testDescription varchar(max), #if_measure char(1), #if_result char(1), #row int = '1', #id int
set #LogEntry = (SELECT REPLACE(#LogEntry,#crlf,','))
declare #name varchar(max),#description varchar(MAX), #measure varchar(20), #result char(1)
declare #Output table(OutTestName varchar(max),OUTTestDescription varchar(max), OutMeasure varchar(50), OutResult varchar(50))
declare #maximum int = (select MAX(ID) from dbo.template_FMT)
declare #LogEntry1 as nvarchar(max)
declare #LogEntry2 as nvarchar(max)
while #row <= #maximum
BEGIN
set #name = null
set #description = null
set #measure = null
set #result = null
set #testname = (select Name from dbo.template_FMT where ID = #row)
set #testDescription = (select TestDescription from dbo.template_FMT where ID = #row)
set #if_measure = (select Measure from dbo.template_FMT where ID = #row)
set #if_result = (select Result from dbo.template_FMT where ID = #row)
set #id = (select ID from dbo.Split(#LogEntry, ',') where Data = #testname)
SELECT #LogEntry1 = Name FROM dbo.template_FMT where id = #row
set #name = #LogEntry1
SELECT #LogEntry2 = TestDescription FROM dbo.template_FMT where id = #row
set #description = #LogEntry2
if #if_measure > 0 and #if_result > 0
begin
set #measure = (select Data from dbo.Split(#LogEntry, ',') where ID = #id+4)
set #result = (select Data from dbo.Split(#LogEntry, ',') where ID = #id+8)
insert into #Output (OutTestName, OUTTestDescription, OutMeasure, OutResult) Values(#name,#description, #measure, #result)
end
if #if_measure > 0 and #if_result = 0
begin
set #measure = (select Data from dbo.Split(#LogEntry, ',') where ID = #id+4)
set #result = null
insert into #Output (OutTestName, OUTTestDescription, OutMeasure, OutResult) Values(#name,#description, #measure, #result)
end
if #if_measure = 0 and #if_result > 0
begin
set #measure = null
set #result = (select Data from dbo.Split(#LogEntry, ',') where ID = #id+4)
insert into #Output (OutTestName, OUTTestDescription, OutMeasure, OutResult) Values(#name,#description, #measure, #result)
end
set #row = #row + 1
END
select * from #Output
And it worked! but the only problem I have is where I have the row with the name Error with the description Error,it would return the last remembered value so instead of having
CAL_MCU Total version reading 05 NULL
Error Error 9.8499985089315E-07 NULL
CAL_EEPROM Total version reading 05 1
I get:
CAL_MCU Total version reading 05 NULL
Error Error 05 NULL
CAL_EEPROM Total version reading 05 1
And I would like to store the Error cant find Result with ID into variables if any of you have any suggestions :)
P.S. I think it has something to do with the fact that the name and description have the same name (Error)
I believe that your problem can be solved without the need for while loops and string splitting functions. I recommend using the OPENROWSET function to read your raw data file as a standard table. You can then use standard T-SQL query to format the result into the desired output.
The first step is to ensure that ad-hoc queries is enable on your server this can be accomplished by executing the following command.
sp_configure 'show advanced options', 1;
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
The next step is to define a format file for your text file. This will help SQL Server understand the text file structure when loading the raw data. Based on the supplied sample data your format file should look as follow:
10.0
4
1 SQLCHAR 0 100 "," 1 Col1 SQL_Latin1_General_CP1_CI_AS
2 SQLCHAR 0 100 "," 2 Col2 SQL_Latin1_General_CP1_CI_AS
3 SQLCHAR 0 100 "," 3 Col3 SQL_Latin1_General_CP1_CI_AS
4 SQLCHAR 0 100 "\r\n" 4 Col4 SQL_Latin1_General_CP1_CI_AS
I have uploaded the format file and example raw data file I have used to test the example at the following links:
http://www.filedropper.com/format
http://www.filedropper.com/rawdatafile
The final step is to run the OPENROWSET query to load the file data and transform the data to the desired output. If you are using SQL Server 2008 r2 then the following query should work:
-- 2008 R2 Version
WITH CTE_VariableRawData
AS
(
SELECT ROW_NUMBER() OVER(ORDER BY (SELECT 0)) AS ID
,[RawData].Col1 AS [VariableOrMeasure]
,(
CASE [RawData].Col4
WHEN '(Result)' THEN 0
WHEN '(Measure)' THEN 0
ELSE 1
END
) AS IsVariable
,(
CASE [RawData].Col4
WHEN '(Result)' THEN 1
ELSE 0
END
) AS IsResult
,(
CASE [RawData].Col4
WHEN '(Measure)' THEN 1
ELSE 0
END
) AS IsMeasure
,[RawData].Col4 AS [Description]
FROM OPENROWSET(BULK N'C:\temp\raw_data_file.txt', FORMATFILE = 'c:\temp\format.txt') AS [RawData]
)
,
CTE_RawDataByVariableID
AS
(
SELECT ID
,(
SELECT SUM([IsVariable])
FROM CTE_VariableRawData RunningTotal
WHERE RunningTotal.ID <= CTE_VariableRawData.ID
) AS VariableID
,[VariableOrMeasure]
,[IsVariable]
,[IsResult]
,[IsMeasure]
,[Description]
FROM CTE_VariableRawData
)
SELECT VariableID
,MAX(
CASE [IsVariable]
WHEN 1 THEN [VariableOrMeasure]
ELSE NULL
END
) AS [Variable]
,MAX(
CASE [IsVariable]
WHEN 1 THEN [Description]
ELSE NULL
END
) AS [Description]
,MAX(
CASE [IsMeasure]
WHEN 1 THEN [VariableOrMeasure]
ELSE NULL
END
) AS [Measure]
,MAX(
CASE [IsResult]
WHEN 1 THEN [VariableOrMeasure]
ELSE NULL
END
) AS [Result]
FROM CTE_RawDataByVariableID
GROUP BY VariableID
ORDER BY VariableID
If you are using SQL Server 2012 or later then the following query will be a bit more optimal:
WITH CTE_VariableRawData
AS
(
SELECT ROW_NUMBER() OVER(ORDER BY (SELECT 0)) AS ID
,[RawData].Col1 AS [VariableOrMeasure]
,(
CASE [RawData].Col4
WHEN '(Result)' THEN 0
WHEN '(Measure)' THEN 0
ELSE 1
END
) AS IsVariable
,(
CASE [RawData].Col4
WHEN '(Result)' THEN 1
ELSE 0
END
) AS IsResult
,(
CASE [RawData].Col4
WHEN '(Measure)' THEN 1
ELSE 0
END
) AS IsMeasure
,[RawData].Col4 AS [Description]
FROM OPENROWSET(BULK N'C:\temp\raw_data_file.txt', FORMATFILE = 'c:\temp\format.txt') AS [RawData]
)
,
CTE_RawDataByVariableID
AS
(
SELECT ID
,SUM([IsVariable]) OVER (ORDER BY ID) AS VariableID
,[VariableOrMeasure]
,[IsVariable]
,[IsResult]
,[IsMeasure]
,[Description]
FROM CTE_VariableRawData
)
SELECT VariableID
,MAX(
CASE [IsVariable]
WHEN 1 THEN [VariableOrMeasure]
ELSE NULL
END
) AS [Variable]
,MAX(
CASE [IsVariable]
WHEN 1 THEN [Description]
ELSE NULL
END
) AS [Description]
,MAX(
CASE [IsMeasure]
WHEN 1 THEN [VariableOrMeasure]
ELSE NULL
END
) AS [Measure]
,MAX(
CASE [IsResult]
WHEN 1 THEN [VariableOrMeasure]
ELSE NULL
END
) AS [Result]
FROM CTE_RawDataByVariableID
GROUP BY VariableID
ORDER BY VariableID;
Note that in both queries you will have to change the location of your raw data file and format file to the desired location within the OPENROWSET(BULK N'C:\temp\raw_data_file.txt', FORMATFILE = 'c:\temp\format.txt') call.

T-SQL Procedure split and join on sub columns

Not really sure how to explain this so I just start with the example.
Say I have a table like this which can include several rows:
id Type Text
1 Test Failure A=123 B=444 C=43343 Error=4 ErroDes=1
I also have a static Error and ErrorDes table which look like this
Id Code Description
1 1 Error1
2 4 Error4
How can I split up the information from the column into seperate fields and also join in the info from the subtables.
Expected result would be something like this:
Type Field1 FieldA FieldB FieldC Error ErrorDes
Test Failure 123 444 43343 Error4 Error1
I used the same table for joining in the example but this is 2 tables in the db.
So to help with this I have a split function in the database.
And if I first split the Text field on "space" and then on "=" I get everything I need (or atleast all the columns in seperate rows)
cross apply dbo.Split(a.Text, ' ') s
cross apply dbo.Split(s.Value, '=') s2
I get "TokenID" and "Value" field back from the split function.
The output from that looks like this:
TokenID Value TokenID Value
1 Failure 1 Failure
2 A=123 1 A
2 A=123 2 123
3 B=444 1 B
3 B=444 2 444
4 C=43343 1 C
4 C=43343 2 43343
5 Error=4 1 Error
5 Error=4 2 4
6 ErrorDes=1 1 ErrorDes
6 ErrorDes=1 2 1
I hope you understand what I ment and can help me how this can be solved.
you can use something like the folowing UDF function to cross apply
create function udf_ReturnTextSplit(#vText varchar(100))
returns #rt table (
Field1 varchar(100),
FieldA varchar(100),
FieldB varchar(100)
) as begin
declare #st varchar(100) = #vText + ' '
declare #sti varchar(100)
declare #stj varchar(100)
insert into #rt (Field1, FieldA, FieldB) values (null, null, null)
declare #i int = charindex(' ', #st)
while #i > 0 begin
set #sti = SUBSTRING(#st, 1, #i)
set #st = substring(#st, #i + 1, 100)
set #i = CHARINDEX('=', #sti)
if #i > 0 begin
set #stj = substring(#sti, #i + 1, 100)
set #sti = substring(#sti, 1, #i - 1)
if #sti = 'A' update #rt set FieldA = #stj
if #sti = 'B' update #rt set FieldB = #stj
end else begin
update #rt set Field1 = #sti
end
set #i = charindex(' ', #st)
end
return
end
go
select * from dbo.udf_ReturnTextSplit('Failure A=123 B=444 C=43343 Error=4 ErroDes=1')

Sorting VARCHAR column with alphanumeric entries

I am using SQL Server, the column is a VARCHAR(50) and I want to sort it like this:
1A
1B
2
2
3
4A
4B
4C
5A
5B
5C
5N
14 Draft
21
22A
22B
23A
23B
23C
23D
23E
25
26
FR01584
MISC
What I have so far is:
Select *
From viewASD
ORDER BY
Case When IsNumeric(LEFT(asdNumNew,1)) = 1
Then CASE When IsNumeric(asdNumNew) = 1
Then Right(Replicate('0',20) + asdNumNew + '0', 20)
Else Right(Replicate('0',20) + asdNumNew, 20)
END
When IsNumeric(LEFT(asdNumNew,1)) = 0
Then Left(asdNumNew + Replicate('',21), 20)
End
But this SQL statement puts '14 Draft' right after '26'.
Could someone help? Thanks
Your WHERE statement is... oddly complex.
It looks like you want to sort by any leading numeric digits in integer order, and then sort by the remainder. If so, you should do that as separate clauses, rather than trying to do it all in one. The specific issue you're having is that you're only allowing for a single-digit number, instead of two or more. (And there's No such thing as two.)
Here's your fix, along with a SQLFiddle, using two separate calculated columns tests for your ORDER BY. (Note that this assumes the numeric portion of asdNumNew will fit in a T-SQL int. If not, you'll need to adjust the CAST and the maximum value on the first ELSE.)
SELECT * FROM viewASD
ORDER BY
CASE
WHEN ISNUMERIC(asdNumNew)=1
THEN CAST(asdNumNew as int)
WHEN PATINDEX('%[^0-9]%',asdNumNew) > 1
THEN CAST(
LEFT(
asdNumNew,
PATINDEX('%[^0-9]%',asdNumNew) - 1
) as int)
ELSE 2147483648
END,
CASE
WHEN ISNUMERIC(asdNumNew)=1
THEN NULL
WHEN PATINDEX('%[^0-9]%',asdNumNew) > 1
THEN SUBSTRING(
asdNumNew,
PATINDEX('%[^0-9]%',asdNumNew) ,
50
)
ELSE asdNumNew
END
If all numbers within the string are reasonably small, say not exceeding 10 digits,
you may expand all the numbers in the string to be exactly 10 digits:
123A -> 0000000123A
S4 -> S0000000004
A3B89 -> A0000000003B0000000089
and so on and then sort them
-- Expand all numbers within S by zeros to be MaxLen
create function [dbo].ExpandNumbers(#S VarChar(4000), #maxlen integer) returns VarChar(4000)
as
begin
declare #result VarChar(4000);
declare #buffer VarChar(4000);
declare #Ch Char;
declare #i integer;
set #buffer = '';
set #result = '';
set #i = 1;
while (#i <= len(#S))
begin
set #Ch = substring(#S, #i, 1);
if ((#Ch >= '0') and (#Ch <= '9'))
set #buffer = #buffer + #Ch
else
begin
if (len(#buffer) > 0)
set #result = #result + right(replicate('0', #maxlen) + #buffer, #maxlen);
set #buffer = '';
set #result = #result + #Ch;
end;
set #i = #i + 1;
end;
if (len(#buffer) > 0)
set #result = #result + right(replicate('0', #maxlen) + #buffer, #maxlen);
return #result;
end;
-- Final query is
select *
from viewASD
order by [dbo].ExpandNumbers(asdNumNew)
I had something similar, but with the possibility of dashes as leading characters as well as trailing spaces. This code worked for me.
SELECT
my_column,
PATINDEX('%[^0-9]%',my_column) AS first_alpha_position,
CONVERT(INT,
CASE
WHEN PATINDEX('%[^0-9]%',my_column) = 0 OR PATINDEX('-%',my_column) = 1
THEN ABS(my_column)
ELSE SUBSTRING(my_column,1,PATINDEX('%[^0-9]%',my_column) -1)
END) AS numeric_value,
LTRIM(
SUBSTRING(my_column,PATINDEX('%[^0-9]%',my_column),LEN(my_column)-PATINDEX('%[^0-9]%',my_column)+1)
) AS alpha_chars
FROM my_table
ORDER BY numeric_value,alpha_chars
TRY THIS
DECLARE #t table (Number nvarchar(20))
INSERT INTO #t
SELECT 'L010'
UNION ALL SELECT 'L011'
UNION ALL SELECT 'L011'
UNION ALL SELECT 'L001'
UNION ALL SELECT 'L012'
UNION ALL SELECT '18'
UNION ALL SELECT '8'
UNION ALL SELECT '17'
UNION ALL SELECT 'B004'
UNION ALL SELECT 'B006'
UNION ALL SELECT 'B008'
UNION ALL SELECT 'B018'
UNION ALL SELECT 'UG001'
UNION ALL SELECT 'UG011'
UNION ALL SELECT 'G001'
UNION ALL SELECT 'G002'
UNION ALL SELECT 'G011';
SELECT Number
FROM #t
ORDER BY
CAST
(
SUBSTRING
(
Number
, 1
, CASE
WHEN patindex('%[^0-9]%',Number) > 0 THEN patindex('%[^0-9]%',Number) - 1
ELSE LEN(Number) END
) AS int
)
, Number
What worked for me is I split up the numeric and the alpha parts and then sorted based on the Alpha, then the Numeric:
CREATE FUNCTION [admin].[GetUnitNumberAsIntFunc](#UnitNumber varchar(20))
RETURNS int
BEGIN
DECLARE #intPosition int
SET #intPosition = PATINDEX('%[^0-9]%', #UnitNumber)
WHILE #intNumber > 0
BEGIN
SET #UnitNumber = STUFF(#UnitNumber, #intNumber, 1, '')
SET #intPosition = PATINDEX('%[^0-9]%', #UnitNumber)
END
RETURN ISNULL(#UnitNumber,9999)
END;
CREATE FUNCTION [admin].[GetUnitNumberAsStrFunc](#UnitNumber varchar(20))
RETURNS varchar(20)
BEGIN
DECLARE #intPosition int
SET #intPosition = PATINDEX('%[0-9]%', #UnitNumber)
SET #UnitNumber = STUFF(#UnitNumber, #intPosition, 6, '')
RETURN ISNULL(#UnitNumber,9999)
END;

SQL Function call in Select Statement to populate Reporting Services Report

I'm trying to return a specific digit for each number in a dataset, I've written an SQL function and now I need to be able to do the calculation in the function for each number in the dataset. Can you please point me in the correct direction? I don't know if I should create a temp table then join that, if I should just write a vb function within Reporting Services and do that or if I just need to start over.
Here is the function
USE [CUDatabase]
GO
/****** Object: UserDefinedFunction [dbo].[fn_Check_Digit] Script Date: 11/13/2012 14:40:59 ******/ SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[fn_Check_Digit]
(
#unique_NBR VARCHAR(MAX)
)
RETURNS #Values TABLE
(
check_digit int,
unique_nbr int
)
AS
BEGIN
-- set up working variables
DECLARE #LEN AS INT
DECLARE #INDEX AS INT
DECLARE #CHAR AS VARCHAR(1)
DECLARE #POSITION AS INT
DECLARE #VALUE AS INT
DECLARE #SUBTOTAL AS INT
DECLARE #BASE AS INT
DECLARE #CHECK_DIG AS INT
SET #LEN = LEN(#MEMBER_NBR)
SET #INDEX = 1
SET #POSITION = 0
SET #VALUE = 0
SET #SUBTOTAL = 0
SET #BASE =0
SET #CHECK_DIG = 0
-- iterate until we have no more characters to work with
WHILE #index<=#len
BEGIN
SET #char = SUBSTRING(#unique_NBR,(#len-#POSITION),1)
select #value = (SELECT scd.dig_mul_value
FROM CUDatabase.DBO.sdcCheckDigit SCD
WHERE SCD.dig_place = #index)
set #value = #value * #char
SET #index = #index + 1
SET #POSITION = #POSITION + 1
SET #SUBTOTAL = #VALUE + #SUBTOTAL
END
SET #BASE = ((#SUBTOTAL/10)+1)*10
IF #BASE -#SUBTOTAL = 10
SET #CHECK_DIG = 0
ELSE
SET #CHECK_DIG = #BASE-#SUBTOTAL
INSERT INTO #Values (check_digit, unique_nbr) VALUES (CAST(#CHECK_DIG AS int),#unique_NBR)
RETURN
END
GO
The table that is in the select statement of that function has the following values in it:
dig_place dig_mul_value
1 7
2 3
3 1
4 7
5 3
6 1
7 7
8 3
9 1
Here is the dataset, I need to loop through each unique_nbr and return the check digit.
`SELECT I.D1NAME,
IA.ADDRESS_ID,
A.ADDRESS1,
A.ADDRESS2,
A.ADDRESS3,
A.CITY,
A.STATE,
A.ZIP_STR,
TL.COMPANY_NAME,
TL.COMPANY_DESCRIPTION,
TL.EFFECTIVE_ENTRY_DATE,
TL.AMOUNT,
TL.ACCOUNT_NBR,
TL.ACCT_DBRN
FROM MEMBERSHIPPARTICIPANT MP
JOIN INDIVIDUAL I ON
I.INDIVIDUAL_ID = MP.INDIVIDUAL_ID
AND I.DL_LOAD_DATE = MP.DL_LOAD_DATE
JOIN INDIVIDUALADDRESS IA ON
IA.INDIVIDUAL_ID = I.INDIVIDUAL_ID
AND IA.IS_PRIMARY = 1
AND IA.DL_LOAD_DATE = I.DL_LOAD_DATE
JOIN ADDRESS A ON
A.ADDRESS_ID = IA.ADDRESS_ID
AND A.DL_LOAD_DATE = IA.DL_LOAD_DATE
JOIN (SELECT EFT.unique_NBR,
EFT.ACCOUNT_NBR,
EFT.ACH_SDC_NBR,
EFT.COMPANY_NAME,
EFT.COMPANY_DESCRIPTION,
EFT.INDIVIDUAL_ID_NBR,
EFT.INDIVIDUAL_NAME,
EFT.XPTIMESTAMP,
EFT.STANDARD_ENTRY_CLASS,
EFT.ROUTING_NUMBER,
EFT.ACCT_DBRN,
EFT.AMOUNT,
EFT.EFFECTIVE_ENTRY_DATE
FROM EFTTRANSACTION EFT
WHERE EFT.ROUTING_NUMBER = 999999999
AND EFT.STANDARD_ENTRY_CLASS IN ('WEB','TEL')
AND EFT.EFFECTIVE_ENTRY_DATE >= '11/01/2012') TL
ON T L.unique_NBR = MP.unique_NBR
WHERE MP.DL_LOAD_DATE = (SELECT MAX(DL_LOAD_DATE) FROM MEMBERSHIPPARTICIPANT)
AND MP.PARTICIPATION_TYPE = 101
--AND MP.unique_NBR = 9835
ORDER BY MP.unique_NBR`
Thanks for any help
All you have to do is call the SQL function you have already created, i.e.
SELECT I.D1NAME,
IA.ADDRESS_ID,
A.ADDRESS1,
A.ADDRESS2,
A.ADDRESS3,
A.CITY,
A.STATE,
A.ZIP_STR,
TL.COMPANY_NAME,
TL.COMPANY_DESCRIPTION,
TL.EFFECTIVE_ENTRY_DATE,
TL.AMOUNT,
TL.ACCOUNT_NBR,
TL.ACCT_DBRN,
dbo.fn_Check_Digit(L.unique_NBR) CheckDigit
FROM .....

Inserting n number of records with T-SQL

I want to add a variable number of records in a table (days)
And I've seen a neat solution for this:
SET #nRecords=DATEDIFF(d,'2009-01-01',getdate())
SET ROWCOUNT #nRecords
INSERT int(identity,0,1) INTO #temp FROM sysobjects a,sysobjects b
SET ROWCOUNT 0
But sadly that doesn't work in a UDF (because the #temp and the SET ROWCOUNT). Any idea how this could be achieved?
At the moment I'm doing it with a WHILE and a table variable, but in terms of performance it's not a good solution.
If you're using SQL 2005 or newer, you can use a recursive CTE to get a list of dates or numbers...
with MyCte AS
(select MyCounter = 0
UNION ALL
SELECT MyCounter + 1
FROM MyCte
where MyCounter < DATEDIFF(d,'2009-01-01',getdate()))
select MyCounter, DATEADD(d, MyCounter, '2009-01-01')
from MyCte
option (maxrecursion 0)
/* output...
MyCounter MyDate
----------- -----------------------
0 2009-01-01 00:00:00.000
1 2009-01-02 00:00:00.000
2 2009-01-03 00:00:00.000
3 2009-01-04 00:00:00.000
4 2009-01-05 00:00:00.000
5 2009-01-06 00:00:00.000
....
170 2009-06-20 00:00:00.000
171 2009-06-21 00:00:00.000
172 2009-06-22 00:00:00.000
173 2009-06-23 00:00:00.000
174 2009-06-24 00:00:00.000
(175 row(s) affected)
*/
You can use a WHILE statement for that:
declare #i int
declare #rows_to_insert int
set #i = 0
set #rows_to_insert = 1000
while #i < #rows_to_insert
begin
INSERT INTO #temp VALUES (#i)
set #i = #i + 1
end
you can use a cross join
select top 100000 row_number() over(order by t1.number)-- here you can change 100000 to a number you want or a variable
from master.dbo.spt_values t1
cross join master.dbo.spt_values t2
When you have a pre-built numbers table, just use that:
SELECT *
FROM numbers
WHERE number <= DATEDIFF(d,'2009-01-01',getdate())
There are any number of techniques for building the numbers table in the first place (using techniques here), but once it's built and indexed, you don't build it again.
this is the approach I'm using and works best for my purposes and using SQL 2000. Because in my case is inside an UDF, I can't use ## or # temporary tables so I use a table variable.
I'm doing:
DECLARE #tblRows TABLE (pos int identity(0,1), num int)
DECLARE #numRows int,#i int
SET #numRows = DATEDIFF(dd,#start,#end) + 1
SET #i=1
WHILE #i<#numRows
begin
INSERT #tblRows SELECT TOP 1 1 FROM sysobjects a
SET #i=#i+1
end
Overall much faster to double the amount of rows at every iteration
CREATE TABLE dbo.Numbers(n INT NOT NULL PRIMARY KEY)
GO
DECLARE #i INT;
SET #i = 1;
INSERT INTO dbo.Numbers(n) SELECT 1;
WHILE #i<128000 BEGIN
INSERT INTO dbo.Numbers(n)
SELECT n + #i FROM dbo.Numbers;
SET #i = #i * 2;
END;
I deliberately did not SET NOCOUNT ON, so that you see how it inserts 1,2,4,8 rows
You could do what PinalDave suggests:
INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
UNION ALL
SELECT 'Fourth' ,4
UNION ALL
SELECT 'Fifth' ,5
GO
How about:
DECLARE #nRecords INT
SET #nRecords=DATEDIFF(d,'2009-01-01',getdate())
SELECT TOP (#nRecords)
ROW_NUMBER() OVER (ORDER BY a.object_id, b.object_id) - 1
FROM sys.objects a, sys.objects b
If you don't want it zero-indexed, remove the " - 1"
Requires at least SQL Server 2005.