How to clear or drop Declared table - temp-tables

How do I clear/reset/drop temporary created table that is in loop?
Another loop at the top with extra code...
How do I reset/drop the declared table up here or below?
Declare #Aresource table(idr int identity(1,1), id int)
Insert into #Aresource (id)
SELECT idr = AssignmentImageId
FROM VLP2014..Assignment
Where AssignmentId = #ida
Declare #ari int
Declare #aricnt int
select #ari = min(idr) - 1, #aricnt = max(idr) from #Aresource
While #ari < #aricnt
Begin
Select #ari = #ari + 1
Declare #arid int
select #arid = id from #Aresource where idr = #ari
How do I reset/drop the declared table here?
some more code...
I have tried the normal DROP TABLE if exists but since it is Declared (temp table) I cant seem to be able to call it.

Fixed issue with adding normal temp table to the db and then removing it after the loop.
Create Table #Aresource (idr int identity(1,1), id int)
Insert into #Aresource (id)
SELECT idr = AssignmentImageId
FROM VLP2014..Assignment
Where AssignmentId = #ida
Declare #ari int
Declare #aricnt int
select #ari = min(idr) - 1, #aricnt = max(idr) from #Aresource
While #ari < #aricnt
Begin
Select #ari = #ari + 1
Declare #arid int
select #arid = id from #Aresource where idr = #ari
...... more code ....
end
Drop table #Aresource

Related

Text values in formulas are limited to 255 characters to create longer text values in formula

I want to insert some big values in an excel sheet, but it is giving errors.
Error
Text values in formulas are limited to 255 characters. To create text
values longer in a formula, use the CONCATENATE
function or the concatenation operator (&).
Value
=CONCATENATE("BEGIN TRY
BEGIN TRANSACTION
BEGIN --User defined values
DECLARE #FieldName NVARCHAR(100) = '",F2,"';
DECLARE #Currencycode VARCHAR(3) = '",A2,"';
DECLARE #Countrycode VARCHAR(2) = '",B2,"';
DECLARE #RuleType NVARCHAR(100) = 'CannotContainSpecialCharOtherThan';
DECLARE #RuleValue INT = 0;
DECLARE #InsFieldTypeDesc NVARCHAR(50) = 'AnyType';
DECLARE #RuleValueAlpha NVARCHAR(4000) = '/: (),.''-?+';
DECLARE #ErrMsg NVARCHAR(500) = '",N2,"';
DECLARE #ErrCode NVARCHAR(10) = '",M2,"';
DECLARE #ErrPrior TINYINT = '",L2,"';
DECLARE #IsLength INT = 0; ---if length is there then set this 1 or 0
DECLARE #DependantOn NVARCHAR(100) = NULL
END
BEGIN --Consts
DECLARE #UTCTime DATETIME = Getutcdate();
DECLARE #CTTime DATETIME = Dateadd(hour, -5, Getutcdate());
END
DECLARE #FieldRuleConfigPk INT;
DECLARE #ErrorMsgpk INT;
DECLARE #countryfk INT;
DECLARE #Fieldnamefk INT;
DECLARE #InsFieldTypeFk INT;
DECLARE #RuleValue1 INT = 0;
DECLARE #RuleValue2 INT = 19;
DECLARE #RuleValue3 INT = 19;
DECLARE #RuleTypeFk INT;
DECLARE #ErrorFk INT;
DECLARE #IsOk INT = 0
PRINT( 'Starts script' )
BEGIN --INIT
SET #countryfk = (SELECT countrypk
FROM mas_country
WHERE countrycode = #Countrycode);
SET #Fieldnamefk = (SELECT fieldnamepk
FROM mas_fieldname
WHERE fieldname = #FieldName);
SET #InsFieldTypeFk = (SELECT instructionfieldtypepk
FROM mas_instructionfieldtype
WHERE fieldtypedesc = #InsFieldTypeDesc);
END
IF NOT EXISTS (SELECT 1
FROM mas_fieldruleconfig
WHERE currencycode = #Currencycode
AND countryfk = #countryfk
AND fieldnamefk = #Fieldnamefk)
BEGIN
INSERT INTO mas_fieldruleconfig
(currencycode,
countryfk,
fieldnamefk,
instructionfieldtypefk,
createddateutc,
createddatect)
VALUES ( #Currencycode,
#countryfk,
#Fieldnamefk,
#InsFieldTypeFk,
#UTCTime,
#CTTime )
SELECT #FieldRuleConfigPk = Scope_identity();
SET #IsOk = 1
PRINT( 'mas_fieldruleconfig insert success' )
END
ELSE
BEGIN
SELECT #FieldRuleConfigPk = fieldruleconfigpk
FROM mas_fieldruleconfig
WHERE currencycode = #Currencycode
AND countryfk = #countryfk
AND fieldnamefk = #Fieldnamefk
PRINT( 'mas_fieldruleconfig setting already exists' )
END
IF NOT EXISTS (SELECT 1
FROM mas_ruletype
WHERE ruletype = #RuleType
AND fieldruleconfigfk = #FieldRuleConfigPk
--Need to add this check, otherwise it will fail
AND rulevalue = #RuleValue --Not needed
AND rulevaluealphanumeric = #RuleValueAlpha)
--Not needed
BEGIN
INSERT INTO mas_ruletype
(ruletype,
fieldruleconfigfk,
rulevalue,
rulevaluealphanumeric,
createddateutc,
createddatect,
dependanton)
VALUES ( #RuleType,
#FieldRuleConfigPk,
#RuleValue,
#RuleValueAlpha,
#UTCTime,
#CTTime,
#DependantOn)
SELECT #RuleTypeFk = Scope_identity();
SET #IsOk = 1
PRINT( 'mas_ruletype insert success' )
END
ELSE
BEGIN
SELECT #RuleTypeFk = (SELECT ruletypepk
FROM mas_ruletype
WHERE ruletype = #RuleType
AND fieldruleconfigfk =
#FieldRuleConfigPk
--Need to add this check, otherwise it will fail
AND rulevalue = #RuleValue
--Not needed
AND rulevaluealphanumeric =
#RuleValueAlpha)
PRINT( 'mas_ruletype settings already exists' )
END
IF NOT EXISTS (SELECT 1
FROM mas_errormessage
WHERE errormessage = #ErrMsg)
BEGIN
INSERT INTO mas_errormessage
(errormessage,
createddateutc,
createddatect)
VALUES ( #ErrMsg,
#UTCTime,
#CTTime )
SELECT #ErrorMsgpk = Scope_identity()
SET #IsOk = 1
PRINT( 'mas_errmsg insert success' )
END
ELSE
BEGIN
SELECT #ErrorMsgpk = errormessagepk
FROM mas_errormessage
WHERE errormessage = #ErrMsg
PRINT( 'mas_errormsg settings already exists' )
END
IF NOT EXISTS (SELECT 1
FROM mas_error
WHERE fieldnamefk = #Fieldnamefk
AND errorcode = #ErrCode)
BEGIN
INSERT INTO mas_error
(fieldnamefk,
errorcode,
errorpriority,
errormessagefk,
createddateutc,
createddatect)
VALUES ( #Fieldnamefk,
#ErrCode,
#ErrPrior,
#ErrorMsgpk,
#UTCTime,
#CTTime )
SELECT #ErrorFk = Scope_identity();
SET #IsOk = 1
PRINT( 'mas_error insert success' )
END
ELSE
BEGIN
SELECT #ErrorFk = (SELECT errorpk
FROM mas_error
WHERE fieldnamefk = #Fieldnamefk
AND errorcode = #ErrCode);
PRINT( 'Mas_Error settings already exists' )
END
IF NOT EXISTS (SELECT 1
FROM [lnk_fieldruleerror]
WHERE [fieldruleconfigfk] = #FieldRuleConfigPk
AND [fieldnamefk] = #Fieldnamefk
AND [ruletypefk] = #RuleTypeFk
AND #ErrorFk = #ErrorFk)
BEGIN
INSERT INTO [dbo].[lnk_fieldruleerror]
([fieldruleconfigfk],
[fieldnamefk],
[ruletypefk],
[errorfk])
VALUES (#FieldRuleConfigPk,
#Fieldnamefk,
#RuleTypeFk,
#ErrorFk)
END
IF #IsOk = 1
BEGIN
COMMIT TRANSACTION
PRINT( 'commit' )
END
END TRY
BEGIN CATCH
PRINT 'Error'
PRINT ( 'Rollback' )
ROLLBACK TRANSACTION;
END CATCH")
I have followed this link also but could not find a solution.
Try breaking it up like this:
=CONCATENATE("BEGIN TRY",CHAR(10),
"BEGIN TRANSACTION",CHAR(10),
"dgd",CHAR(10),
"dfh",CHAR(10),
etc.
);
I have solved by splitting the value into multiple cells and merging these into a new cell like this =A2&" "&B2

I cant insert my values into my SQLite table

So I have been working roughly all the Christmas with this, but it seems like I cant actually find a way, I just create this account because of it. So, lets go into the code.
In first stance, I wanna warning the variables and all that are in spanish, but I dont think it will be a problem.
I have been taking a lot of data, its... if I recall correctly 53 or 56 columns in my SQL table or something like. I have been recollecting data through all the app and getting it through each activity by "putExtra". This is for a project for my school, so I have to use SQLite (I would like to use firebase, being honest) so, whatever, lets go into the code, which is the important stuff.
#Override
public void onCreate(SQLiteDatabase BaseDeDatos) {
//Creamos instancia a nuestra clase de BD
BaseDeDatos.execSQL("create table datos_personaje (apellido text primary key, nombre text, edad int, genero text, raza text, clase text, " +
"fuerza int, destreza int, resistencia int, inteligencia int, percepcion int, voluntad int, carisma int, apariencia int, manipulacion int, " +
"pelea int, atletismo int, robar int, sigilo int, nadar int, montar int, abrirCerr int, resDolorF int, escalar int, evadir int, esquivar int, bloquear int, " +
"alerta int, supervivencia int, coherencia int, rastrear int, concentracion int, buscar int, esconderse int, resDolorM int, estrategia int, escuchar int, conGeneral int, tasar int, " +
"mentir int, empatia int, liderazgo int, intimidar int, callejeo int, comercio int, seducir int, protocolo int, convencer int, actuar int, timar int, disfraz int, " +
"tecnicasHechizos text, inventario text)");
}
This is the creation of the table, I would say its alright.
public void SQLiteAyuda() {
Bundle extras = getIntent().getExtras();
String nombre = extras.getString("nombre");
String apellidos = extras.getString("apellidos");
int edad = extras.getInt("edad");
String genero = extras.getString("genero");
String raza = extras.getString("raza");
String clase = extras.getString("clase");
int f = extras.getInt("principalesF");
int d = extras.getInt("principalesD");
int r = extras.getInt("principalesR");
int i = extras.getInt("principalesI");
int p = extras.getInt("principalesP");
int v = extras.getInt("principalesV");
int c = extras.getInt("principalesC");
int a = extras.getInt("principalesA");
int m = extras.getInt("principalesM");
int pelea = extras.getInt("pelea");
int atletismo = extras.getInt("atletismo");
int robar = extras.getInt("robar");
int sigilo = extras.getInt("sigilo");
int nadar = extras.getInt("nadar");
int montar = extras.getInt("montar");
int abrirCerr = extras.getInt("abrircerr");
int resDolorF = extras.getInt("resdolorf");
int escalar = extras.getInt("escalar");
int evadir = extras.getInt("evadir");
int bloquear = extras.getInt("bloquear");
int esquivar = extras.getInt("esquivar");
int alerta = extras.getInt("alerta");
int supervivencia = extras.getInt("supervivencia");
int coherencia = extras.getInt("coherencia");
int rastrear = extras.getInt("rastrear");
int concentracion = extras.getInt("concentracion");
int buscar = extras.getInt("buscar");
int esconderse = extras.getInt("esconderse");
int resDolorM = extras.getInt("resDolorM");
int estrategia = extras.getInt("estrategia");
int escuchar = extras.getInt("escuchar");
int conGeneral = extras.getInt("conGeneral");
int tasar = extras.getInt("tasar");
int mentir = extras.getInt("mentir");
int empatia = extras.getInt("empatia");
int liderazgo = extras.getInt("liderazgo");
int intimidar = extras.getInt("intimidar");
int callejeo = extras.getInt("callejeo");
int comercio = extras.getInt("comercio");
int seducir = extras.getInt("seducir");
int protocolo = extras.getInt("protocolo");
int convencer = extras.getInt("convencer");
int actuar = extras.getInt("actuar");
int timar = extras.getInt("conGeneral");
int disfraz = extras.getInt("disfraz");
String poderes = extras.getString("tecnicasHechizos");
String inventario = inventarioText.getText().toString();
I get all my data in the last activity, so I can get it into the SQL table:
AdminSQLiteOpenHelper admin = new AdminSQLiteOpenHelper(this, "datos_personaje", null, 2);
SQLiteDatabase BaseDeDatos = admin.getWritableDatabase();
ContentValues datos = new ContentValues();
datos.put("nombre", nombre);
datos.put("apellido", apellidos);
datos.put("edad", edad);
datos.put("genero", genero);
datos.put("raza", r);
datos.put("clase", c);
datos.put("fuerza", f);
datos.put("destreza", d);
datos.put("resistencia", r);
datos.put("inteligencia", i);
datos.put("percepcion", p);
datos.put("voluntad", v);
datos.put("carisma", c);
datos.put("apariencia", a);
datos.put("manipulacion", m);
datos.put("pelea", pelea);
datos.put("atletismo", atletismo);
datos.put("robar", robar);
datos.put("sigilo", sigilo);
datos.put("nadar", nadar);
datos.put("montar", montar);
datos.put("abrircerr", abrirCerr);
datos.put("resdolorf", resDolorF);
datos.put("escalar", escalar);
datos.put("evadir", evadir);
datos.put("esquivar", esquivar);
datos.put("bloquear", bloquear);
datos.put("alerta", alerta);
datos.put("supervivencia", supervivencia);
datos.put("coherencia", coherencia);
datos.put("rastrear", rastrear);
datos.put("concentracion", concentracion);
datos.put("buscar", buscar);
datos.put("esconderse", esconderse);
datos.put("resDolorM", resDolorM);
datos.put("estrategia", estrategia);
datos.put("escuchar", escuchar);
datos.put("conGeneral", conGeneral);
datos.put("tasar", tasar);
datos.put("mentir", mentir);
datos.put("empatia", empatia);
datos.put("liderazgo", liderazgo);
datos.put("intimidar", intimidar);
datos.put("callejeo", callejeo);
datos.put("comercio", comercio);
datos.put("seducir", seducir);
datos.put("protocolo", protocolo);
datos.put("convencer", convencer);
datos.put("actuar", actuar);
datos.put("timar", timar);
datos.put("disfraz", disfraz);
datos.put("tecnicasHechizos", poderes);
datos.put("inventario", inventario);
BaseDeDatos.insert("datos_personaje", null, datos);
BaseDeDatos.close();
And the debugger shows me the next output:
E/SQLiteLog: (1)
E/SQLiteDatabase: Error inserting table datos_personaje has no column named coherencia (Sqlite code 1): , while compiling: INSERT INTO datos_personaje(esconderse,sigilo,protocolo,resdolorf,carisma,genero,destreza,inventario,escalar,alerta,liderazgo,raza,rastrear,escuchar,inteligencia,pelea,edad,disfraz,abrircerr,buscar,manipulacion,comercio,evadir,nadar,actuar,resDolorM,bloquear,conGeneral,resistencia,coherencia,mentir,apariencia,estrategia,tasar,montar,esquivar,robar,nombre,fuerza,clase,supervivencia,atletismo,callejeo,apellido,intimidar,timar,tecnicasHechizos,concentracion,voluntad,percepcion,seducir,convencer,empatia) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?), (OS error - 2:No such file or directory)

MemSQL - populate a table using comma separate string value

I need to pass a list of values to a MemSQL procedure.
Is there a way of transforming the comma separated integer values from the input string into a table.
MemSQL doesn't yet have something like the python string split function that converts a delimited string into an array of strings. In MemSQL 6.5, the best method would be to do something like this using the locate builtin function.
delimiter //
create or replace procedure insert_split_string(input text, d text) as
declare
position int = 1;
newPosition int = -1;
begin
while newPosition != 0 loop
newPosition = locate(d, input, position);
if newPosition != 0 then
insert into t values(substring(input, position, newPosition - position));
position = newPosition + 1;
end if;
end loop;
-- Add the last delimited element
insert into t values(substring_index(input, d, -1));
end //
delimiter ;
create table t(i int);
call insert_split_string("1,2,3,4,5", ",");
select * from t;

Compatible SQL function for Excel FDist

Does anyone know that is there a compatible function in SQL for Excel FDIST and FINV? If there is no, anyone has any idea how to build that? May be in C#?
Thanks. Your help is greatly appreciated.
I have managed to resolve my problems by using a library from .Net Framework 4.0 and above (System.Windows.Forms.DataVisualization.Charting.StatisticFormula).
I am able to develop a function in C# using the above library for my calculation process. This is a powerful library where you can find mostly common use statistical formula in there (e.g. mean, median, t distribution, f distribution, and inverse of them.)
Below are the code snippet from me:
using System.Windows.Forms.DataVisualization.Charting;
private Chart ch = new Chart(); // You will need to declare an object of Chart type, as Statistic Formula class does not have a public constructor
double fDist = ch.DataManipulator.Statistics.FDistribution(fRatioVariance, degreeFreedom1, degreeFreedom2);
Hope this will help others. Thanks.
Though its too late but below are some statistical function implementation in SQL Server itself.
To get FDist function (equivalent to Excel - FDist), we will be needing Complete and Incomplete beta function as well as gamma function:
--GAMMA Function
CREATE FUNCTION [dbo].[udf_Gamma]
(
#x Float=NULL
)
RETURNS Float
AS
BEGIN
Declare #f Float = 10E99;
Declare #g Float = 1;
if ( #x > 0 )
Begin
while (#x < 3)
Begin
SET #g = #g * #x;
SET #x = #x + 1;
End
SET #f = (1 - (2/(7*power(#x,2))) * (1 - 2/(3*power(#x,2))))/(30*power(#x,2));
SET #f = (1-#f)/(12*#x) + #x*(log(#x)-1);
SET #f = (exp(#f)/#g)*power(2*PI()/#x,0.5);
End
else
Begin
SET #f = 10E99
End
return #f;
END
--BETA Complete Function
CREATE FUNCTION [dbo].[udf_BetaC]
(
#x Float=NULL
,#a Float=NULL
,#b Float=NULL
)
RETURNS Float
AS
BEGIN
--double betacf(double a,double b,double x){
Declare #maxIterations int = 50, #m int =1
Declare #eps Float = 3E-5
Declare #am Float = 1;
Declare #bm Float = 1;
Declare #az Float = 1;
Declare #qab Float = #a+#b;
Declare #qap Float = #a+1;
Declare #qam Float = #a-1;
Declare #bz Float = 1 - #qab*#x/#qap;
Declare #aold Float = 0;
Declare #em Float, #tem Float, #d Float, #ap Float, #bp Float, #app Float, #bpp Float;
while((#m<#maxIterations) AND (abs(#az-#aold)>=#eps*abs(#az)))
Begin
SET #em = #m;
SET #tem = #em+#em;
SET #d = #em*(#b-#m)*#x/((#qam + #tem)*(#a+#tem));
SET #ap = #az+#d*#am;
SET #bp = #bz+#d*#bm;
SET #d = -(#a+#em)*(#qab+#em)*#x/((#a+#tem)*(#qap+#tem));
SET #app = #ap+#d*#az;
SET #bpp = #bp+#d*#bz;
SET #aold = #az;
SET #am = #ap/#bpp;
SET #bm = #bp/#bpp;
SET #az = #app/#bpp;
SET #bz = 1;
SET #m = #m + 1;
End
return #az
END
--BETA INCOMPLETE Function
CREATE FUNCTION [dbo].[udf_BetaI]
(
#x Float=null
,#a Float=null
,#b Float=null
)
RETURNS Float
AS
BEGIN
Declare #bt Float=0.0
Declare #beta Float=0.0
if( #x=0 OR #x=1 )
Begin
SET #bt = 0
End
else if((#x>0) AND (#x<1))
Begin
SET #bt = (Select dbo.UDF_Gamma(#a+#b)* power(#x,#a)* power(1-#x,#b)/(dbo.UDF_Gamma(#a)*dbo.UDF_Gamma(#b)) )
End
if(#x<(#a+1)/(#a+#b+2))
Begin
SET #beta = (Select #bt*dbo.udf_betaC(#x,#a,#b)/#a)
End
else
Begin
SET #beta = (Select 1-#bt*dbo.udf_betaC(1-#x,#b,#a)/#b)
End
Return #beta
END
--FDist Function
CREATE FUNCTION [dbo].[udf_FDist]
(
#x Float=NULL
,#df1 Float=NULL
,#df2 Float=NULL
)
RETURNS Float
AS
BEGIN
Declare #x1 Float=(#x*#df1)/((#x*#df1)+#df2)
return (select 1 - dbo.udf_BetaI(#x1,(#df1/2),(#df2/2)))
END
Check in Excel =FDIST(0.5,1,1)=0.608173448
and in SQL editor = SELECT udf_FDIST(0.5,1,1)=0.608173457369209
Regards,
Avi
FDIST an FINV Don't exists IN Sql Server.
You can write a SQL Sever function to implement two excel feature.
Show here to create function
in MS SQL Server there is standard_deviation
and some more statistical functions including variance.
There is also a million workarounds, for example: http://oreilly.com/catalog/transqlcook/chapter/ch08.html
,you need to dig deep into the math for these, though.

Need to cut a string(Table Name) from Query in c#

My String/Query looks like this
insert into Employee Values(1,2,'xxx');
update Employee2 set col1='xxx' where col2='yyy';
select * from Employee3;
I need to take/have TableName alone. Table name won't be constant it will be differed(Employee,Employee2,Employee3) according to DB. I'm new to C# please help me. Thanks in advance.
To get the name of a table from a query (or in this case, a string named 'sql'), try the following:
string sql = "select * from table ";
int index1 = 0;
int index2 = 0;
int currentIndex = 0;
int numSpaces = 0;
char[] chArray = sql.ToCharArray();
foreach (char c in chArray)
{
if (c == ' ')
{
numSpaces++;
if (numSpaces == 3)
index1 = currentIndex;
if (numSpaces == 4)
{
index2 = currentIndex;
break;
}
}
currentIndex++;
}
int length = index2 - index1;
string tableName = sql.Substring(index1, length);
MessageBox.Show(tableName);
Warning - this solution is based on finding the word between the 3rd and 4th space character. This limits you to have a very predictable query structure - more complicated queries may not work with this solution. Your query structure needs to be:
"select column_name1,column_name2,column_name3 from table "
Your query must not have spaces between columns and must have a space at the end aswell. Sorry for the limitations but its the best I can come up with ;)

Resources