Using Lookup function to pull in specific contentblockby ID in an email with ampscript - salesforce-marketing-cloud

Can I pull in a specific contentblockbyID using the lookup function in ampscript based on the conditional IF/ELSE statement?

Yes. You can use a dynamic variable within your Lookup statement. Here is an example. I have a table with my group names and their respective content block ids. I can use an if statement to set the group name and then use that variable in my Lookup to return the value I needed.
In your email:
%%[
if #p_type=1 then
set #CB_type = "A"
else then
set #CB_type = "B"
endif
set #CB_ID = Lookup("TABLENAME","CONTENTBLOCK_IDS","NAME",#CB_type)
]%%
%%=CONTENTBLOCKBYID(#CB_ID)=%%
DATA EXTENSION NAME: "TABLE NAME"
COLUMNS - NAME / CONTENTBLOCK_IDS
Row 1 - A / 123
Row 2 - B / 124
Here are some great resources:
AMPSCRIPTGUIDE - IF Statements
AMPSCRIPTGUIDE - LOOKUP Function
AMPSCRIPTGUIDE - CONTENTBLOCKBYID Function

Related

Django bulk update setting each to different values? [duplicate]

I'd like to update a table with Django - something like this in raw SQL:
update tbl_name set name = 'foo' where name = 'bar'
My first result is something like this - but that's nasty, isn't it?
list = ModelClass.objects.filter(name = 'bar')
for obj in list:
obj.name = 'foo'
obj.save()
Is there a more elegant way?
Update:
Django 2.2 version now has a bulk_update.
Old answer:
Refer to the following django documentation section
Updating multiple objects at once
In short you should be able to use:
ModelClass.objects.filter(name='bar').update(name="foo")
You can also use F objects to do things like incrementing rows:
from django.db.models import F
Entry.objects.all().update(n_pingbacks=F('n_pingbacks') + 1)
See the documentation.
However, note that:
This won't use ModelClass.save method (so if you have some logic inside it won't be triggered).
No django signals will be emitted.
You can't perform an .update() on a sliced QuerySet, it must be on an original QuerySet so you'll need to lean on the .filter() and .exclude() methods.
Consider using django-bulk-update found here on GitHub.
Install: pip install django-bulk-update
Implement: (code taken directly from projects ReadMe file)
from bulk_update.helper import bulk_update
random_names = ['Walter', 'The Dude', 'Donny', 'Jesus']
people = Person.objects.all()
for person in people:
r = random.randrange(4)
person.name = random_names[r]
bulk_update(people) # updates all columns using the default db
Update: As Marc points out in the comments this is not suitable for updating thousands of rows at once. Though it is suitable for smaller batches 10's to 100's. The size of the batch that is right for you depends on your CPU and query complexity. This tool is more like a wheel barrow than a dump truck.
Django 2.2 version now has a bulk_update method (release notes).
https://docs.djangoproject.com/en/stable/ref/models/querysets/#bulk-update
Example:
# get a pk: record dictionary of existing records
updates = YourModel.objects.filter(...).in_bulk()
....
# do something with the updates dict
....
if hasattr(YourModel.objects, 'bulk_update') and updates:
# Use the new method
YourModel.objects.bulk_update(updates.values(), [list the fields to update], batch_size=100)
else:
# The old & slow way
with transaction.atomic():
for obj in updates.values():
obj.save(update_fields=[list the fields to update])
If you want to set the same value on a collection of rows, you can use the update() method combined with any query term to update all rows in one query:
some_list = ModelClass.objects.filter(some condition).values('id')
ModelClass.objects.filter(pk__in=some_list).update(foo=bar)
If you want to update a collection of rows with different values depending on some condition, you can in best case batch the updates according to values. Let's say you have 1000 rows where you want to set a column to one of X values, then you could prepare the batches beforehand and then only run X update-queries (each essentially having the form of the first example above) + the initial SELECT-query.
If every row requires a unique value there is no way to avoid one query per update. Perhaps look into other architectures like CQRS/Event sourcing if you need performance in this latter case.
Here is a useful content which i found in internet regarding the above question
https://www.sankalpjonna.com/learn-django/running-a-bulk-update-with-django
The inefficient way
model_qs= ModelClass.objects.filter(name = 'bar')
for obj in model_qs:
obj.name = 'foo'
obj.save()
The efficient way
ModelClass.objects.filter(name = 'bar').update(name="foo") # for single value 'foo' or add loop
Using bulk_update
update_list = []
model_qs= ModelClass.objects.filter(name = 'bar')
for model_obj in model_qs:
model_obj.name = "foo" # Or what ever the value is for simplicty im providing foo only
update_list.append(model_obj)
ModelClass.objects.bulk_update(update_list,['name'])
Using an atomic transaction
from django.db import transaction
with transaction.atomic():
model_qs = ModelClass.objects.filter(name = 'bar')
for obj in model_qs:
ModelClass.objects.filter(name = 'bar').update(name="foo")
Any Up Votes ? Thanks in advance : Thank you for keep an attention ;)
To update with same value we can simply use this
ModelClass.objects.filter(name = 'bar').update(name='foo')
To update with different values
ob_list = ModelClass.objects.filter(name = 'bar')
obj_to_be_update = []
for obj in obj_list:
obj.name = "Dear "+obj.name
obj_to_be_update.append(obj)
ModelClass.objects.bulk_update(obj_to_be_update, ['name'], batch_size=1000)
It won't trigger save signal every time instead we keep all the objects to be updated on the list and trigger update signal at once.
IT returns number of objects are updated in table.
update_counts = ModelClass.objects.filter(name='bar').update(name="foo")
You can refer this link to get more information on bulk update and create.
Bulk update and Create

Hiding table or assigning temp data based on visibility expression ssrs 2008

I have a table in ssrs 2008. This table has a row visibility expression like:
=IIF(max(Fields!VExpected.Value) <> "", 1, 0) +
IIF(max(Fields!MExpected.Value) <> "", 1, 0) +
IIF(max(Fields!PExpected.Value) <> "", 1, 0) = 3, false, true)
Sometimes the datasource returns no data, or the returned data is not matching with this expression. In this case what I see is that a table with borders and column names but no data on it like:
id Vex Mex Pex
However, I want to show it as
id Vex Mex Pex
- - - -
Or if possible:
id Vex Mex Pex
No Data
Another question is, is there any way to hide the complete table if there is no returning data or any matching data with the expression?
Thanks
You can use CountRows function to determine how many rows your dataset is returning. If it is zero hide the table otherwise show it.
=iif(CountRows("DataSetName")=0,true,false)
Replace DataSetName by the actual name of your dataset.
For not matching expression data you can use the this expression.
=IIF(
max(Fields!VExpected.Value) <> "" AND
max(Fields!MExpected.Value) <> "" AND
max(Fields!PExpected.Value) <> "",False,True
)
The whole expression for matching expression and no rows cases could be something like this:
=Switch(
CountRows("DataSetName")=0,true,
max(Fields!VExpected.Value) = "",true,
max(Fields!MExpected.Value) = "",true,
max(Fields!PExpected.Value) = "",True,
true,False
)
Supposing VM, ME and PE expected values are numeric type I'd use ISNOTHING() function to determine when null values are being returned.
=Switch(
CountRows("DataSetName")=0,true,
ISNOTHING(max(Fields!VExpected.Value)),true,
ISNOTHING(max(Fields!MExpected.Value)),true,
ISNOTHING(max(Fields!PExpected.Value)),True,
true,False
)
Additional you can set a message when no rows are being returned from your dataset. Select the tablix and press F4 to see properties window. Go to NoRowsMessage property and use an expression to say your users there is no data.
="There is no data."
In this cases the tablix will not appear in your report but the message you set will be rendered in the location where the tablix should be.
Let me know if this helps.

How to hide a row in ssrs using a multi select parameter

I need to be able to conditionally hide a row in SSRS 2005 based on a Multi Select Parameter. I need to be able to hide the row if the multi parameter = "CS", but if the Multi select Parameter is "CS" and "Sales" then I need to see the row.
I've tried this formula:
=IIf((Parameters!Level_4.Value(0) = "CS"
And Parameters!Level_4.Value(0) = "Sales"),false ,True)
=IIF((Parameters!Level_4.Value(0) = "CS"), True, False)
But it does not work...
Try this:
=Switch(
Array.IndexOf(Parameters!Level_4.Value, "CS")>-1 AND
Array.IndexOf(Parameters!Level_4.Value, "Sales")>-1,false,
Array.IndexOf(Parameters!Level_4.Value, "CS")>-1,true
)
Note multivalued parameters can contain one or multiple values which are stored in an array data type. So if you select a value in your report it will be stored in the 0 index of the array, if you select one more value it will be stored in the 1 index and so on.
Example: "CS" value is stored in Level_4.Value(0) and "Sales" is stored in Level_4.Value(1).
The expression I proposed will check if both values were selected and return true in that case, otherwise if only "CS" is selected it will return false.
UPDATE: Alternative to IndexOf support
=Switch(
InStr(Join(Parameters!Level_4.Value, ","),"CS")>0 AND
InStr(Join(Parameters!Level_4.Value, ","),"Sales")>0,false,
InStr(Join(Parameters!Level_4.Value, ","),"CS")>0,true
)
Let me know if this helps.

MySQL Dynamic Query Statement in Python with Dictionary

Very similar to this question MySQL Dynamic Query Statement in Python
However what I am looking to do instead of two lists is to use a dictionary
Let's say i have this dictionary
instance_insert = {
# sql column variable value
'instance_id' : 'instnace.id',
'customer_id' : 'customer.id',
'os' : 'instance.platform',
}
And I want to populate a mysql database with an insert statement using sql column as the sql column name and the variable name as the variable that will hold the value that is to be inserted into the mysql table.
Kind of lost because I don't understand exactly what this statement does, but was pulled from the question that I posted where he was using two lists to do what he wanted.
sql = "INSERT INTO instance_info_test VALUES (%s);" % ', '.join('?' for _ in instance_insert)
cur.execute (sql, instance_insert)
Also I would like it to be dynamic in the sense that I can add/remove columns to the dictionary
Before you post, you might want to try searching for something more specific to your question. For instance, when I Googled "python mysqldb insert dictionary", I found a good answer on the first page, at http://mail.python.org/pipermail/tutor/2010-December/080701.html. Relevant part:
Here's what I came up with when I tried to make a generalized version
of the above:
def add_row(cursor, tablename, rowdict):
# XXX tablename not sanitized
# XXX test for allowed keys is case-sensitive
# filter out keys that are not column names
cursor.execute("describe %s" % tablename)
allowed_keys = set(row[0] for row in cursor.fetchall())
keys = allowed_keys.intersection(rowdict)
if len(rowdict) > len(keys):
unknown_keys = set(rowdict) - allowed_keys
print >> sys.stderr, "skipping keys:", ", ".join(unknown_keys)
columns = ", ".join(keys)
values_template = ", ".join(["%s"] * len(keys))
sql = "insert into %s (%s) values (%s)" % (
tablename, columns, values_template)
values = tuple(rowdict[key] for key in keys)
cursor.execute(sql, values)
filename = ...
tablename = ...
db = MySQLdb.connect(...)
cursor = db.cursor()
with open(filename) as instream:
row = json.load(instream)
add_row(cursor, tablename, row)
Peter
If you know your inputs will always be valid (table name is valid, columns are present in the table), and you're not importing from a JSON file as the example is, you can simplify this function. But it'll accomplish what you want to accomplish. While it may initially seem like DictCursor would be helpful, it looks like DictCursor is useful for returning a dictionary of values, but it can't execute from a dict.

Change image name and update into same table using mysql query

I want to change image name in table like below.
image name : test.png
replace with : test_E.png
I want _E at end of all image name in table using mysql query.
Use replace function
update <table>
set image=replace(image,'.png','_E.png')
you could use this, if the image extension is not same in the table
update <table>
set image=concat(substring(image,1,locate('.',image)-1),'_E',
substring(image,locate('.',image),lenght(image)))
You can use string functions of MySQL query:
UPDATE TABLE SET IMAGE_NAME = CONCAT(SUBSTR(IMAGE_NAME,(CHAR_LENGTH(IMAGE_NAME) - 4)),
'_E' , SUBSTR(IMAGE_NAME, -4)) WHERE ID = <put record id>;
SUBSTR(IMAGE_NAME,(CHAR_LENGTH(IMAGE_NAME)-4)) would return name of file - assuming extension is of 3 chars. For 'test.png' above function would remove '.png' and function would return 'test'
SUBSTR(IMAGE_NAME, -4) would return last four chars of string - so 'test.png' would return '.png'
using concat you can concat 'test', '_E' and '.png' - returning 'test_E.png'
Please refer to string functions reference of MySQL for further use
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html