Declare #var INT = 10
SELECT * from dbo.school where class = #var
This is how we declare in SQL.
How do I do the same in Spark SQL in data bricks?
val i = 10
val sqlS = s"SELECT * from dbo.school where class = $i"
val df = spark.sql(sqlS)
Related
I'm working with a few different databases that all have the same stored procedure, but some have been updated while others haven't.
Suppose I have this entity:
#NamedStoredProcedureQueries(
NamedStoredProcedureQuery(
name = "getData",
procedureName = "dbo.selClientByStatus",
resultClasses = [MonitorData::class],
parameters = [
StoredProcedureParameter(name = "lowerRange", type = Int::class, mode=ParameterMode.IN),
StoredProcedureParameter(name = "upperRange", type = Int::class, mode=ParameterMode.IN),
StoredProcedureParameter(name = "connectionStatus", type = Int::class, mode=ParameterMode.IN),
StoredProcedureParameter(name = "serverID", type = String::class, mode=ParameterMode.IN),
]
)
)
#Entity
data class MonitorData(
#Id
#Column(name = "serverId")
val serverId: Int? = null,
#Column(name = "displayName")
val displayName: String? = null,
#Column(name = "providerId")
val providerId: Int? = null
)
When I call the stored procedure with:
em?.createNamedStoredProcedureQuery("getData")
?.setParameter("lowerRange", null)
?.setParameter("upperRange", null)
?.setParameter("connectionStatus", null)
?.resultList
Some databases have providerId as a select in the stored procedure, but some don't. It's not really a necessary field, but it can help with sorting, etc. When a stored procedure doesn't select providerId I understandably get a(n) SQLServerException saying The column providerId is not valid.
Is it possible to ignore that field if it doesn't exist in the resultList?
I currently have a TABLE object, as below and existing table in DB. I am creating a webservice using KTOR.
object Arts: Table() {
val id : Column<Int> = integer("id").autoIncrement().primaryKey()
val title = varchar("title" , 256)
val description = varchar("desc", 512)
val price = double("price")
}
I would like to add a column, last_modified how to alter the current table.
First, add the column last_modified to your table.
object Arts: Table() {
val id : Column<Int> = integer("id").autoIncrement().primaryKey()
val title = varchar("title" , 256)
val description = varchar("desc", 512)
val price = double("price")
val lastModified = datetime("last_modified").defaultExpression(CurrentDateTime())
}
Then call the function
SchemaUtils.createMissingTablesAndColumns(Arts)
How to convert sql to system.linq?
Select top 100 percent s.a,s.b,s.c,s.d
From table a as s, table b as x
Where
s.a=x.a and s.b=x.b and s.c=x.c
Group by
s.a,s.b,s.c,s.d
As per my understanding of your question; seems like you want to fetch the data in c# and do joining. if so, then you may do as following:
public class tabData
{
public string a {get;set;}
public string b {get;set;}
public string c {get;set;}
public string d {get;set;}
}
List<tabData> tabA = {data of your table a}
List<tabData> tabB = {data of your table b}
var result = from r1 in tabA
join r2 in tabB on new {T1 = r1.a, T2 = r1.b, T3 = r1.c} equals new {T1 = r2.a, T2 = r2.b, T3 = r2.c}
group r1 by new
{
aa = r1.a,
bb = r1.b,
cc = r1.c,
dd = r1.d
} into g
select new
{
a = g.key.aa,
b = g.key.bb,
c = g.key.cc,
d = g.key.dd
}
I think you are asking how to join in linq as you would in sql, if so, please see below:
var query =
from abc in tbl1
join def in tbl2 on tbl1.PK equals tbl2.FK
select new { ABC = abc, DEF = def };
Can someone help me convert this SQL Query to EntityFramework LINQ?
DECLARE #UserId varchar(50) = '123'
SELECT
TL.TrackId,
COUNT(*) AS LikeCount,
(SELECT IIF(COUNT(*) > 0, 'true','false') FROM UserTrackLikes WHERE
UserId = #UserId AND TrackId = TL.TrackId) AS IsLiked
FROM TrackList AS TL
LEFT OUTER JOIN UserTrackLikes AS UTL
ON UTL.TrackId = TL.TrackId
GROUP BY TL.TrackId
You can use the query syntax:
int userId = 123;
var result = (from trackList in context.TrackLists
select new
{
trackList.TrackId,
LikeCount = trackList.Likes.Count(),
IsLiked = trackList.Likes.Any(x => x.UserId == userId)
}).ToList();
Assuming that here, Likes is a collection of UserTrackLike, declared like this:
public ICollection<UserTrackLike> Likes { get; set; }
here is the class I set up for my database. database handler being the inner class.
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.content.ContentValues
import android.util.Log
import java.sql.Date
class Scores {
var id : Int = 0
var dataBaseName = "ScoreDatabase"
var averageTime = 0.0f
val date = Date(System.currentTimeMillis()).toString()
constructor(averageTime:Float) {
this.averageTime = averageTime
Log.d("Poop", averageTime.toString())
}
constructor()
inner class DataBaseHandler(var context:Context, tableName:String): SQLiteOpenHelper(context, dataBaseName, null,1){
val TABLE_NAME = tableName
val COL_ID = "id"
val COL_AVG = "Average_Time"
val COL_DATE = "Date"
override fun onCreate(db: SQLiteDatabase?) {
val createTable = "CREATE TABLE " + TABLE_NAME +" (" +
COL_ID +" INTEGER PRIMARY KEY AUTOINCREMENT," +
COL_AVG + " VARCHAR(256)," +
COL_DATE +" VARCHAR(256)"
db?.execSQL(createTable)
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
fun insertData(score: Scores){
val db = this.writableDatabase
var cv = ContentValues()
cv.put(COL_AVG,score.averageTime)
cv.put(COL_DATE,score.date)
var result = db.insert(TABLE_NAME,null,cv)
if(result == -1.toLong())
Log.d("POOP", "fail score table in addition")
else
Log.d("POOP", "Success score table in addition" )
}
fun readData(): MutableList<Scores>{
var list: MutableList<Scores> = ArrayList()
val db = this.readableDatabase
val query = "Select * from $TABLE_NAME"
val result = db.rawQuery(query,null)
if (result.moveToFirst()){
do {
var score = Scores()
var id = result.getString(0).toInt()
var AvgTime = result.getString(1).toFloat()
var date = result.getString(2).toString()
list.add(score)
}while (result.moveToNext())
}
result.close()
db.close()
return list
}
}
}
I tried this where the scores class and the handler were two separate classes, but it generated the same results.
here is how I write to the database (from 4 separate activities. in each activity the tablename is different. in this one for example it is 'additionDataBase')
val scores = Scores("%.3f".format(timeKeeper.averageNumber).toFloat())
val db = scores.DataBaseHandler(context, "additionDataBase")
db.insertData(scores)
and here is how I read from the database which is in a different activity that shows the averageTime from each table. here is the code for one of them
val context: Context? = activity
val adb = Scores().DataBaseHandler(context!!,"additionDataBase")
val data = adb.readData()
TextViewAdScore.text = data[0].averageTime.toString() + " " + data[1].date
I think I am missing something, but I can't seem to find what it is.
so far, no matter how many times I do this. the output is always 0.0f
Look at what you do in readData:
var score = Scores()
var id = result.getString(0).toInt()
var AvgTime = result.getString(1).toFloat()
var date = result.getString(2).toString()
list.add(score)
id, AvgTime, and date are retrieved but not used in any way, so your code is equivalent to just writing list.add(Scores()). (Side note: there's no reason for them to be var, and why the case inconsistency between AvgTime and the rest?)